【问题标题】:loop for two files only prints first line python两个文件的循环只打印第一行python
【发布时间】:2015-02-02 06:03:47
【问题描述】:
- 第一个文件
f1 有两列,第一列是ID number,第二列是value associated。
- 第二个文件
f2 是第一个文件的更大版本,具有更多值和six columns,但包含第一个文件中的两个。
- 第二个文件有一个我想与第一个文件中的值关联的列,我希望输出是一个新的
text file,其中包含ID,
- 关联的值和另一列与我想从较大的第二个文件中关联的值。
- 到目前为止,我已经编写了一个代码,它可以做我想做的事情,但是它只打印出第一行。
-
我在 python 方面并不出色,这在我的代码中可能很明显,我希望有人能解答我的问题
import csv
with open('output1.txt','w') as out1,open('list1.csv') as f1,open('list2.csv') as f2:
csvf1=csv.reader(f1)
csvf2=csv.reader(f2)
for txt1 in csvf1:
id1=txt1[0]
z1=txt1[1]
for txt2 in csvf2:
id2=txt2[0]
z2=txt2[3]
ra=txt2[1]
if id1==id2:
out1.write("{} {} {}\n".format(id2,z1,ra))
out1.close()
f1.close()
f2.close()
我还想指出,出于某种原因,使用 .split(',') 对我的文件不起作用,以防有人试图在答案中使用它。
【问题讨论】:
标签:
python
file
loops
line
【解决方案1】:
将 csvf2=csv.reader(f2) 行保留在第一个循环内。内部循环将仅在第一行执行。对于第二行,不会执行内部循环,因为文件读取器标记已经在文件末尾。
import csv
with open('output1.txt','w') as out1,open('list1.csv') as f1,open('list2.csv') as f2:
csvf1=csv.reader(f1)
for txt1 in csvf1:
id1=txt1[0]
z1=txt1[1]
csvf2=csv.reader(f2)
for txt2 in csvf2:
id2=txt2[0]
z2=txt2[3]
ra=txt2[1]
if id1==id2:
out1.write("{} {} {}\n".format(id2,z1,ra))
out1.close()
f1.close()
f2.close()
【解决方案2】:
cvs.reader() 是一个函数,你只能迭代它的结果一次,(它是一个yield 函数吗?有人应该纠正我,我只是深入研究源代码并卡在对象reader() 的buildin-module。无论如何,它的行为就像一个yield 函数)
因此您可能需要将每一行保存在临时数组中以供进一步使用:
list1 = []
with open('list1.txt') as fp:
for row in csv.reader(fp):
list1.append(row)
顺便说一句,当您使用 with 表达式打开 fp 时,您不需要显式关闭它,当您离开 with 范围时,该机制会为您执行此操作。
【解决方案3】:
我设法从另一个程序员那里找到了我的答案,这就是最终工作的代码。
非常感谢您的回答,因为它们接近有效的方法。
import csv
with open('output1.txt','w') as out1, open('file1.csv') as f1:
csvf1=csv.reader(f1)
for txt1 in csvf1:
id1=txt1[0]
z1=txt1[1]
with open('file2.csv') as f2:
csvf2=csv.reader(f2)
for txt2 in csvf2:
id2=txt2[0]
z2=txt2[3]
ra=txt2[1]
if id1 == id2:
out1.write("{} {} {}\n".format(id2,z1,ra))