Python关于文件的读取
小甲鱼课后第29讲问题:def judge():
file_name_1 = input('请输入需要比较的头一个文件名(带扩展名):')
file_name_2 = input('请输入需要比较的另一个文件名(带扩展名):')
file_1 = open(file_name_1)
file_2 = open(file_name_2)
count = 0
list1 = []
p1 = file_1.seek(0, 2)
p2 = file_2.seek(0, 2)
file_1.seek(0, 0)
file_2.seek(0, 0)
while True:
if file_1.readline() != file_2.readline():
count += 1
list1.append(count)
if file_1.tell() == p1 and file_2.tell() == p2:
break
file_1.close()
file_2.close()
print('两个文件共有【%d】处不用:' % count)
for each in list1:
print('第%d行不一样' % each)
judge()
我已开始这样写为什么结果一直错误?
后面我改成这样就对了:
def judge():
file_name_1 = input('请输入需要比较的头一个文件名(带扩展名):')
file_name_2 = input('请输入需要比较的另一个文件名(带扩展名):')
file_1 = open(file_name_1)
file_2 = open(file_name_2)
count = 0
list1 = []
list2 = []
list3 = []
for each_line in file_1:
list1.append(each_line)
for each_line in file_2:
list2.append(each_line)
len1 = len(list1)
len2 = len(list2)
x= (len1 if len1 > len2 else len2)
for i in range(x):
if list1 != list2:
count += 1
list3.append(i+1)
file_1.close()
file_2.close()
print('两个文件共有【%d】处不用:' % count)
for each in list3:
print('第%d行不一样' % each)
judge()
我感觉这两段代码实现的方法基本一样啊? 本帖最后由 lumber2388779 于 2017-4-20 09:35 编辑
因为你第一份代码count变化只有在file_1.readline() != file_2.readline()
那你的count统计的只是不同的行数,并没有随行数增加,所以你list1存储的其实只是count的累加过程,就是1-n而已
第二份代码i会随读取的行数变化而变化,所以就是对的
修改代码如下
def judge():
file_name_1 = input('请输入需要比较的头一个文件名(带扩展名):')
file_name_2 = input('请输入需要比较的另一个文件名(带扩展名):')
file_1 = open(file_name_1)
file_2 = open(file_name_2)
count = 0
lines = 0
list1 = []
p1 = file_1.seek(0, 2)
p2 = file_2.seek(0, 2)
file_1.seek(0, 0)
file_2.seek(0, 0)
while True:
lines += 1
if file_1.readline() != file_2.readline():
count += 1
list1.append(lines)
if file_1.tell() == p1 and file_2.tell() == p2:
break
file_1.close()
file_2.close()
print('两个文件共有【%d】处不用:' % count)
for each in list1:
print('第%d行不一样' % each)
judge() lumber2388779 发表于 2017-4-20 09:32
因为你第一份代码count变化只有在file_1.readline() != file_2.readline()
那你的count统计的只是不同的行 ...
懂了 谢谢!果然没考虑周全
页:
[1]