Python CSV,如何在逐行(逐行)读取数据的同时在一行的末尾追加数据? [英] Python CSV, How to append data at the end of a row whilst reading it line by line (row by row)?

查看:73
本文介绍了Python CSV,如何在逐行(逐行)读取数据的同时在一行的末尾追加数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在读取一个名为CSV文件:逐行(逐行),如下所示:

I am reading a CSV file called: candidates.csv line by line (row by row) like follows:

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函数返回的数据?这是我尝试过的:

How can I append the data that the check_updates function returns at the end of the line (row) that I am reading? Here is what I have tried:

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

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

Also not entirely sure that this would have added in the right place at the end of the row that I was reading.

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

Bottom line, how to best add data at the end of the row that I am currently reading?

推荐答案

请先备份文件,以防万一.

您可以编写一个新的临时文件,然后将其移到读取的旧文件上.

You can write a new temporary file and move that into the place over the old file you read from.

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)

这篇关于Python CSV,如何在逐行(逐行)读取数据的同时在一行的末尾追加数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆