如何同时读取多个输入(文本)文件,并在计算后再次打印?

2024-10-01 22:34:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个输入来自两个不同的字典(单独的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 

Tags: 文件txtdataaswithopenwordfile
3条回答

你基本上就在那里。你需要在每一行中重复读一次数据。现在你不是。您可以使用zip将来自不同文件的行配对在一起。在

就我个人而言,我会使用发电机(因为我喜欢发电机),但这不是必要的。在

def read_lines(file_path):
    with open(file_path, 'r') as fh:
        for line in fh:
            yield line

data1 = read_lines(r"/Documents/file1.txt")
data2 = read_lines(r"/Documents/file2.txt")
data = zip(data1, data2)

with open(r"/Documents/output.txt", 'w') as fh:
    for left, right in data:
        equal = left == right
        line = "word:{left}: {right}: {equal}\n".format(left=left.strip(), 
                                                        right=right.strip(), 
                                                        equal=equal)
        fh.write(line)

以下是您问题的答案:

with open("file1", 'r') as f1, open("file2", 'r') as f2:
    j= 0
    data2 = [k.strip("\n").strip() for k in f2.readlines()]
    for line in f1:
        if j == len(data2):
            break
        if line.strip("\n").strip() == data2[j:j+1][0]:
            output = "word:{0}:{1} = {2}".format(line.strip("\n").strip(), data2[j:j+1][0], 1)
        else:
            output = "word:{0}:{1} = {2}".format(line.strip("\n").strip(), data2[j:j+1][0], 0)
        j += 1

        with open("output_file", 'a') as out:
            out.write(output + "\n")

输出:

^{pr2}$

您可以使用readlines将文件读入列表,然后迭代比较:

with open('file1.txt', 'r') as f:
    data1 = f.readlines()
with open('file2.txt', 'r') as f:
    data2 = f.readlines()
data = zip(data1, data2)
with open('output.txt', 'a') as f:
    for x in data:
        out = '{} : {} : {}\n'.format(x[0].strip(), x[1].strip(), x[0] == x[1])
        f.write(out)

相关问题 更多 >

    热门问题