簡體   English   中英

從CSV文件中讀取並在python中寫入新的CSV文件

[英]Readind from a CSV file and writing to a new CSV file in python

說明:我需要從file1中獲取參數並需要在某個函數中使用,然后我需要從該函數中獲取結果,然后需要將這些test_name和結果寫入新的csv即file2中。 而iam用下面的示例iam做一些錯誤。

使用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語句,則您的操作需要在該塊內, 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM