Skip to main content
 首页 » 编程设计

python之如何逐行循环遍历两个文件

2025年05月04日14artech

<分区>

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

我的示例数据文件 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()