|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
1. 编写一个程序,比较用户输入的两个文件,如果不同,显示出所有不同处的行号与第一个不同字符的位置,程序实现如图:
我写的代码在Mac系统下会报错,在win系统下能正常运行,想知道Mac系统下报错的原因是什么?
Mac中报错的内容:
请输入需要比较的第一个文件名:OpenMe.txt
请输入需要比较的第二个文件名:OpenMe2.txt
Traceback (most recent call last):
File "/Users/wxl0311/Desktop/学习/python/编程.py", line 12, in <module>
for each_line in f1:
File "/Library/Frameworks/Python.framework/Versions/3.10/lib/python3.10/codecs.py", line 322, in decode
(result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb3 in position 0: invalid start byte
我编写的代码:
file1 = input("请输入需要比较的第一个文件名:")
file2 = input("请输入需要比较的第二个文件名:")
file1_context = []
file2_context = []
mistake = []
times = 0
f1 = open(file1,"r")
f2 = open(file2,"r")
for each_line in f1:
file1_context.append(each_line)
for each_line in f2:
file2_context.append(each_line)
f1.close()
f2.close()
if len(file1_context) >= len(file2_context):
lenth = len(file2_context)
else:
lenth = len(file1_context)
for i in range(lenth):
if not file1_context[i] == file2_context[i]:
mistake.append(i)
times+=1
print("两个文件共有【{}】处不同:".format(times))
for each in mistake:
print('第{}行不一样'.format(each))
报错原因是文件编码和Python中的 open 函数打开编码不一致导致的
在两个 open 函数中设置 encoding = "gbk"
参考代码:
file1 = input("请输入需要比较的第一个文件名:")
file2 = input("请输入需要比较的第二个文件名:")
file1_context = []
file2_context = []
mistake = []
times = 0
f1 = open(file1,"r", encoding = "gbk")
f2 = open(file2,"r", encoding = "gbk")
for each_line in f1:
file1_context.append(each_line)
for each_line in f2:
file2_context.append(each_line)
f1.close()
f2.close()
if len(file1_context) >= len(file2_context):
lenth = len(file2_context)
else:
lenth = len(file1_context)
for i in range(lenth):
if not file1_context[i] == file2_context[i]:
mistake.append(i)
times+=1
print("两个文件共有【{}】处不同:".format(times))
for each in mistake:
print('第{}行不一样'.format(each))
即可,甲鱼哥的文件编码一般是 gbk
|
|