2017-06-23 143 views
0

说明:我需要从file1中获取参数,并且需要在某些函数中使用,然后我需要从该函数获取结果,然后需要写入这些test_name和结果到一个新的CSV文件2。而我下面的例子iam做了一些错误。从CSV文件中读取并在Python中写入新的CSV文件

Readind从一个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 
+0

请在你的问题中粘贴确切的错误信息和回溯,“一些错误”不是一个非常有用的信息! –

+0

只是使用'pandas' – danche

+2

安装'pandas'只是为了读取一个csv文件是矫枉过正... –

回答

1

如果您使用的是with statment,您的操作需要是块内,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

+1

true,但与开放(inputs.csv,'rb')作为file1,打开('output.csv','wb')作为file2'似乎更可读 - 尤其是因为有一个级别的缩进更少... –

+0

@hiroprotagonist,我同意,这将是一个更可读的解决方案,并将更好地工作,如果有两个文件上的很多操作。 –

+0

感谢@NickHale工作 –