编写一个函数compare(file1,file2),比较两个文本文件内容是否相同。在主程
序中输入两个要比较的两文件名,然后调用以上函数,文件内容相同则输出“No
difference!”;否则,输出从第几个字符开始不相同。
提取出的csv与原csv进行对比,将内容错误的行写入file3,同时附赠错误提示
file1:提取出的csv
file2:原csv
file3:有误内容
def compare_file(file1,file2,file3):
#定义空列表来存放两个文件的对应行engname1,engname2,country1,country2,chiname1,chiname2
#字符串存放对比会出现的错误情况engnameerror,countryerror,chinameeeror
#open打开提取的文件 别名f1,f2
#readlines()读取文件中的每一行 存放在fileone,filetwo
#将fileone中的每一列分离出来,添加进列表中
for row in fileone:
engname1.append(row.split(',')[0])
try:
country1.append(row.split(',')[1])
chiname1.append(row.split(',')[2])
except IndexError : #可能会出现索引越界
country1.append(' ')
chiname1.append(' ')
#同理将filetwo中的每一列分离出来,添加进列表中
#打开file3
#循环第一列的单元格
for cell in engname1:
#比较文件中的第一列,若fileone中的第一列中的元素不在filetwo的第一列的对应行中,将这一行写进file3中
if cell not in engname2:
csvrow=fileone[engname1.index(cell)]+engnameerror
writer.writerow(csvrow.split(','))
#若第一列在,则比较第二列,若fileone中的第二列中的元素不在filetwo的第二列对应行中,将这一行写进file3中
#若第一列,第二列都对应,则比较第三列,若fileone中的第三列中的元素不在filetwo的第三列对应行中,将这一行写进file3中
#关闭文件
运行结果
有误的行写入different.csv,同时在行尾显示错误信息
运行问题
问题抛出:UnicodeDecodeError: 'utf8' codec can't decode byte 0xa4 in position
解决措施:先将文件另存为csv,再用记事本打开,点击文件->另存为,在最下方修改编码方式
def compare(file1, file2):
with open(file1, 'r') as f1, open(file2, 'r') as f2:
content1 = f1.read()
content2 = f2.read()
if content1 == content2:
print("No difference!")
else:
i = 0
while i < len(content1) and i < len(content2):
if content1[i] != content2[i]:
print("Difference starting from the", i+1, "character.")
return
i += 1
print("The two files have different lengths.")
首先,打开文件并读取文件内容。然后直接比较两个文件内容是否相同,如果是,则输出"No difference!"。如果不同,则遍历两个文件的内容,如果存在不同之处,则输出从哪一个字符开始不同。最后在主程序中通过输入两个文件名,调用该函数即可。