gpt4 book ai didi

python - 两个文件的差异检查器并显示哪些行不同

转载 作者:行者123 更新时间:2023-12-01 06:27:11 26 4
gpt4 key购买 nike

您好,我正在编写这段代码,

我有两个文件standard.txt、new.txt

standard.txt 有:ABC123ABC003ABC004new.txt 有:ABC123ABC004

我能够显示文件中的差异,但我感兴趣的是实际显示哪一行有差异。如果有人可以帮忙看一下,也许给我一个我做错了什么的例子,那将会非常有帮助我的代码是:

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"

并使用枚举?

最佳答案

enumeratezip你的 friend 在这里吗?为了获得差异,我会这样做:

# Make sure both lists of lines are same length (for zip)
maxl = max(len(list1), len(list2))
list1 += [''] * (maxl - len(list1))
list2 += [''] * (maxl - len(list2))

for iline, (l1, l2) in enumerate(zip(list1, list2)):
if l1 != l2:
print(iline, l1, l2)

另外,(1) 你不应该使用 list 作为变量名,因为它是 python 中的内置类名,(2) 要从文件中获取所有行一行如下:

lines = open('path_to_file').read().splitlines()

关于python - 两个文件的差异检查器并显示哪些行不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60079436/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com