你好,我有这段代码,我一直在处理,
我有两个文件standard.txt,new.txt
standard.txt 有:ABC123 ABC003 ABC004 new.txt 有:ABC123 ABC004
我能够显示文件中的差异,但我有兴趣实际显示哪一行有差异。如果有人可以帮忙看看,也许给我一个我做错了什么的例子,那将非常有帮助,我的代码是:
def open_file_and_return_list(file_path):
list = []
with open(file_path, 'r') as f:
line = f.readline()
while line:
list.append(line)
line = f.readline()
return list
def clean_new_line(list):
for i in range(len(list)):
if "\n" in list[i]:
list[i] = list[i].replace("\n", "")
return list
if __name__ == "__main__":
list1 = open_file_and_return_list(r"C:\Users\a\a\b\file_compare\new.txt")
list2 = open_file_and_return_list(r"C:\Users\a\a\b\file_compare\standard.txt")
list1 = clean_new_line(list1)
list2 = clean_new_line(list2)
diff = []
for obj in list1:
if obj not in list2:
diff.append(obj)
for obj in list2:
if obj not in list1:
diff.append(obj)
print(diff)
diff_file = input("\nINFO: Select what to name the difference(s) : ")
with open(diff_file, 'w') as file_out:
for line in diff:
file_out.write("** WARNING: Difference found in New Config:\n " + line + "\n")
print("WARNING: Difference in file: " + line)
例如,我正在比较的文件是两个配置文件,因此差异可能会显示在两个不同的行上,因此我不想将每个差异显示为 1、2、3,而是说例如在第 105 行找到的差异: *****区别***
也许我需要做一些事情来解决这个问题?
for i,lines2 in enumerate(hosts1):
if lines2 != lines1[i]:
print "line ", i, " in hosts1 is different \n"
print lines2
else:
print "same"
并使用枚举?
汪汪一只猫
慕桂英546537
相关分类