【发布时间】:2019-08-23 16:53:24
【问题描述】:
我有三个文件,两个正在打开以供阅读,最后一个正在写入。我想遍历一个读取文件中的每一行并检查该行是否存在于另一个读取文件中。然后将相同的行输出到写入文件,如果不存在则为空白。我无法弄清楚如何将一行与所有行进行比较并为每一行进行比较。
我在示例文本文件中尝试了以下代码:
import os
file_path = os.getcwd()
output_file = os.path.join(file_path, "output_file.txt")
read_file1 = os.path.join(file_path, "read_file1.txt")
read_file2 = os.path.join(file_path, "read_file2.txt")
with open(output_file, 'w+') as write:
write.write("")
with open(read_file1, 'r') as read1:
with open(read_file2, 'r') as read2:
with open(output_file, 'a+') as write1:
for line in read1:
if line in read2:
write1.write(line)
else:
write1.write("blank\n")
read_file1 的内容:
test1
test2
test4
test6
test8
test9
test44
test109
read_file2 的内容:
test1
test2
test3
test4
test5
test6
test8
test9
test11
test44
test45
test99
test109
test276
output_file 中的预期输出为:
test1
test2
blank
test4
blank
test6
test8
test9
blank
test44
blank
blank
test109
blank
我得到的输出是:
test1
test2
test4
test6
test8
test9
test44
blank
【问题讨论】:
标签: python python-3.x loops