Python CSV,如何在逐行逐行读取数据的同时在行尾添加数据?

问题描述

我正在逐行(逐行)读取名为以下文件的CSV文件

import csv
for line in open('candidates.csv'):
    csv_row = line.strip().split(',')
    check_update(csv_row[7]) #check_update is a function that returns an int

如何在我正在读取的行(行)的末尾附加check_updates函数返回的数据? 这是我尝试过的:

for line in open('candidates.csv'):
    csv_row = line.strip().split(',')
    data_to_add = check_update(csv_row[7])
    with open('candidates.csv','a') as f:
        writer = csv.writer(f)
        writer.writerow(data_to_add)

出现此错误

_csv.Error: iterable expected,not nonetype

也不完全确定该添加到我正在阅读的行的末尾的正确位置。

底线,如何最好地在当前正在读取的行末添加数据?

解决方法

请备份文件,以防万一。

您可以编写一个新的临时文件,并将其移至您读取的旧文件上。

from tempfile import NamedTemporaryFile
import shutil
import csv

filename = 'candidates.csv'
tempfile = NamedTemporaryFile('w',delete=False)

with open(filename,'r',newline='') as csvFile,tempfile:
    writer = csv.writer(tempfile)

    for line in csvFile:
        csv_row = line.strip().split(',')
        csv_row.append(check_update(csv_row[7])) # this will add the data to the end of the list.
        writer.writerow(csv_row)

shutil.move(tempfile.name,filename)