|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
题目要求:比较用户输入的两个文件,如果不同,显示出所有不同的行号和第一个不同字符的位置。
def read_file(file1,file2):
f1 = open('file1.txt','r')
f2 = open('file2.txt','r')
count = 0 #统计行数
differ = [] #统计不一样数量
for each1 in f1:
each2 = f2.readline()
count += 1
if each1 != each2:
differ.append(count)
f1.close()
f2.close()
return differ
file1 = input('please input the first file: ')
file2 = input('please input the second file: ')
differ = read_file(file1,file2)
if len(differ) == 0:
print('These two files are same!')
else:
print('There are %d difference' %len(differ))
for each in differ:
print('第%d行不一样' %differ)
我的问题是:按照这样写,如果一行有两处不同,是不是也只会输出一处?
是的,因为这段代码是统计不一样的行数,而非不同有多少处
- if each1 != each2:
- differ.append(count)
复制代码
这是我们的判断条件,很显然,两行有差异,是不会去区分有几处不同的
|
|