从CSV文件读取并在python中写入新的CSV文件

时间:2017-06-23 09:48:16

标签: python csv

说明:我需要从file1获取参数并需要在某个函数中使用然后我需要从该函数获取结果然后需要将这些test_name和结果写入新的csv,即file2。虽然我在下面的例子中做了一些错误。

从CSV文件1中读取并使用python

写入新的CSV文件2
with open(inputs.csv, 'rb') as file1:  #Need to read params from this file
    data = list(csv.reader(file1))
with open('output.csv', 'wb') as file2: #Need to write results to this file
    writer = csv.writer(file2)
for row in data:
    api = row[0]
    test_name =row[1]
    out = funtion_call(api, test_name)
    writer.writerow([test_name, out])
file1.close()
file2.close()

输出:

 writer.writerow([test_name, out])
ValueError: I/O operation on closed file

1 个答案:

答案 0 :(得分:1)

如果您使用with声明,则您的操作需要在该块内,with会处理您的开启和关闭。

with open(inputs.csv, 'rb') as file1:  
    data = list(csv.reader(file1))
    with open('output.csv', 'wb') as file2: 
        writer = csv.writer(file2)
        for row in data:
        api = row[0]
        test_name =row[1]
        out = funtion_call(api, test_name)
        writer.writerow([test_name, out])

如果没有你的所有代码,就不可能对此进行测试,但希望你能得到这个想法。此链接也可能有所帮助:http://effbot.org/zone/python-with-statement.htm

相关问题