如何逐行循环浏览两个文件?

时间:2017-05-01 18:30:48

标签: python loops

我试图运行这两个文件行,连接每个文件中的每个单词,但是它会读取整个文件。

我的示例数据文件1:

work
play

我的示例数据文件2:

ed
ing 

我希望这个结果将两个单词连接在一起:

worked
playing  

但我得到了:

working 
worked 
playing
played 

我只是想从每个文件中逐行阅读:

我的代码:

file1 = []


file2 = []


with open('file1.txt','rU') as f:
    for line in f:
        #print line.rstrip()
       file1.append(line.rstrip())


with open('file2.txt','rU') as f1: #cnn-lm input
    for line1 in f1:
       #print line1.rstrip()
       file2.append(line1.rstrip())


resutl=[]
f=open('output.txt', "w")

for i in file1 :
    for g  in file2 :

            temp=[]
            temp.append(i)
            temp.append(g)


                w = (i + g) 

            temp.append(w)
            result=i+','+g+','+str(w)

            f.write(result)
            f.write('\n')
            print w
f.close()

2 个答案:

答案 0 :(得分:5)

这是预期的,因为您正在进行双重循环,即您的条款的产品

你必须用一个简单的循环和zip交错它们,如下所示:

with open('file1.txt','rU') as f1, open('file2.txt','rU') as f2:
    for s,e in zip(f1,f2):
        print("{}{}".format(s.rstrip(),e.rstrip()))

我得到了

working
played

答案 1 :(得分:2)

最简单的解决方案是将文件压缩在一起,并将输出文件包含在同一个with块中。

with open('file1.txt','rU') as f1, open('file2.txt', 'rU') as f2, open('output.txt', "w") as fo:
    for line1, line2 in zip(f1, f2):
        fo.write("{}{}\n".format(line1.rstrip(), line2.rstrip()))