|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
比较两个文件的不同之处
n = 0 #行数
count = [] #不同的数量
file1 = input('请输入需要比较的第一个文件名:')
file2 = input('请输入需要比较的第二个文件名:')
f1 = open(file1+'.txt',encoding = 'utf-8')
f2 = open(file2+'.txt',encoding = 'utf-8')
for line1 in f1:
line2 = f2.readline()
n += 1
if line1 != line2:
count.append(n)
if len(count) == 0:
print('两个文件完全一样')
else:
print('一共%d处不同'%len(count))
for each in count:
print('第%d行不同'%each)
f1.close()
f2.close()
蓝色部分有人能给标注以下嘛,还有,如果想打印出不同的那几行,该怎么改
[b] - # for 循环遍历 f1 文件对象,也是按行遍历,所以每循环一次,就从 f1 文件对象中读取一行内容
- for line1 in f1:
-
- # 使用 readline() 函数从 f2 文件对象中读取一行内容
- line2 = f2.readline()
-
- # n 用于记录行数,for 循环每执行一次,那么就有一行数据被读取,即行数 +1
- n += 1
-
- # 判断两个文件对象此行内容是否相同
- if line1 != line2:
-
- # 若不相同,则将 n 记录下来,即添加如 count 列表中
- count.append(n)
复制代码
不知道是否是这个意思,参考代码:
- n = 0
- count = []
- linetext = []
- file1 = input('请输入需要比较的第一个文件名:')
- file2 = input('请输入需要比较的第二个文件名:')
- f1 = open(file1+'.txt',encoding = 'utf-8')
- f2 = open(file2+'.txt',encoding = 'utf-8')
- for line1 in f1:
- line2 = f2.readline()
- n += 1
- if line1 != line2:
- count.append(n)
- linetext.append([line1, line2])
- if len(count) == 0:
- print('两个文件完全一样')
- else:
- print('一共%d处不同'%len(count))
- for i in range(len(count)):
- print('第%d行不同' % count[i])
- print('\t%s文件第%d行内容为:%s' % (file1, count[i], linetext[i][0]))
- print('\t%s文件第%d行内容为:%s' % (file2, count[i], linetext[i][1]))
- f1.close()
- f2.close()
复制代码
[/b]
|
|