2 回答
TA贡献1898条经验 获得超8个赞
我能够完成我想要混合一堆你的方法。谢谢你!
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"new.txt")
list2 = open_file_and_return_list(r"standard.txt")
maxl = max(len(list1), len(list2))
list1 += [''] * (maxl - len(list1))
list2 += [''] * (maxl - len(list2))
diff = []
diff_file = input("\nINFO: Select what to name the difference(s) : ")
open('diff.txt', 'w').close()
for iline, (l1, l2) in enumerate(zip(list1, list2)):
if l1 != l2:
print(iline, l1, l2)
print(iline, l1, l2, file=open('diff.txt', 'a'))
TA贡献1848条经验 获得超10个赞
enumerate和zip是你的朋友。为了获得差异,我会做类似的事情:
# 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()
添加回答
举报