我有两个输入来自两个不同的字典(单独的txt文件),我想逐行阅读两个文件,比较和打印结果在一个txt文件。(循环) 我的两个输入是这样的
eshark
white
shark
shark
carcharodon
carcharias
以及
^{pr2}$我试过了
with open('file1.txt', 'r') as f1: # for the first file
data = f1.read()
with open('file2.txt', 'r') as f2:
data1 = f2.read()
output = data == data1 # output is 1(true) or 0 (false)
with open("Output1.txt", "w") as text_file
text_file.write("word: %s :%s :%f" % (data ,data1 , output ))
我也试过了,但问题是一样的
with open('file1.txt') as f1,open('file2.txt') as f2:
当我的数据来自一个文件时,我得到了正确的输出,但当我尝试使用两个文件时,我得到了以下输出:
word:shark
white
shark
shark
carcharodon
carcharias
:shark
同时,我想要这个输出
word:etench : 0
word:white : tinca : 0
word:shark : goldfish : 0
word:shark : carassius : 0
word:carcharodon : auratus : 0
word:carcharias : great : 0
你基本上就在那里。你需要在每一行中重复读一次数据。现在你不是。您可以使用
zip
将来自不同文件的行配对在一起。在就我个人而言,我会使用发电机(因为我喜欢发电机),但这不是必要的。在
以下是您问题的答案:
输出:
^{pr2}$您可以使用readlines将文件读入列表,然后迭代比较:
相关问题 更多 >
编程相关推荐