课后作业
本帖最后由 Twilight6 于 2020-7-14 11:55 编辑为什么会这样子QAQ。。。
def compare(file1,file2):
list1 = []
list2 = []
e = open(file1)
f = open(file2)
for each_line in file1:
list1.append(each_line)
for each_line in file2:
list2.append(each_line)
e.close()
f.close()
length = len(list1)
count = 0
list3 = []
for i in range(length):
if list1 != list2:
i += 1
count += 1
list3.append(i)
print('两个文件共有【%d】不同' % count)
for each in list3:
print('第%d行不一样'% each)
print('请输入需要比较的第一个文件名:', end='')
file1 = input()
print('请输入需要比较的第二个文件名:', end='')
file2 = input()
compare(file1,file2)
它只比较了第一行,还比较错了 def花 发表于 2020-7-14 12:04
它只比较了第一行,还比较错了
你for 循环的是文件名,而不是文件对象了:
for each_line in file1:
for each_line in file2:
改成:
for each_line in e:
for each_line in f:
而且你代码有些小错误,比如当 file1 文件更多行的时候,就会导致你第三个 for 循环过程超出范围导致报错
正确参考代码:
def compare(file1, file2):
list1 = []
list2 = []
e = open(file1)
f = open(file2)
for each_line in e:
list1.append(each_line)
for each_line in f:
list2.append(each_line)
e.close()
f.close()
length = len(list2) if len(list1) > len(list2) else len(list1)
count = 0
list3 = []
for i in range(length):
if list1 != list2:
i += 1
count += 1
list3.append(i)
temp = abs(len(list1) - len(list2))
if temp != 0:
list3 += list(range(length,length+temp+1))
count += temp
print('两个文件共有【%d】不同' % count)
for each in list3:
print('第%d行不一样' % each)
print('请输入需要比较的第一个文件名:', end='')
file1 = input()
print('请输入需要比较的第二个文件名:', end='')
file2 = input()
compare(file1, file2) Twilight6 发表于 2020-7-14 13:43
你for 循环的是文件名,而不是文件对象了:
懂了
页:
[1]