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

从CSV文件中读取并在python中写入新的CSV文件,python,csv,Python,Csv,说明:我需要从文件1中获取参数,并需要在某些函数中使用,然后我需要从该函数中获取结果,然后需要将这些测试名称和结果写入新的csv,即文件2。当我在做下面的例子时,我发现了一些错误 使用python从CSV文件1读取并写入新的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

说明:我需要从文件1中获取参数,并需要在某些函数中使用,然后我需要从该函数中获取结果,然后需要将这些测试名称和结果写入新的csv,即文件2。当我在做下面的例子时,我发现了一些错误

使用python从CSV文件1读取并写入新的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
如果您使用with STATTION,您的操作需要在该块内,并为您处理打开和关闭操作

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])

如果没有所有的代码,就不可能对其进行测试,但希望您能理解。此链接也可能有帮助:

请粘贴准确的错误消息并在问题中回溯,有些错误不是非常有用的信息!仅仅为了读取csv文件而使用pandas安装pandas是过分的…使用openinputs.csv,“rb”作为文件1:也许这应该是:使用open“inputs.csv”,“r”作为文件1:。为什么是“rb”和“wb”?您正在读取美化的文本文件。不是bytes files.hi@selten98,当iam仅使用单个文件从csv(即文件1)读取时,其与“rb”配合良好。我也尝试过使用你的建议,但错误是一样的,但使用openinputs.csv,“rb”作为文件1,打开“output.csv”,“wb”作为文件2似乎更可读-特别是因为缩进少了一个级别…@hiroprotation,我同意,这将是一个更具可读性的解决方案,如果在这两个文件上有很多操作,那么效果会更好。