簡體   English   中英

Python CSV,如何在一行一行(一行一行)讀取數據的同時在行尾追加數據?

[英]Python CSV, How to append data at the end of a row whilst reading it line by line (row by row)?

我正在讀取一個名為:Candidates.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)

暫無
暫無

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

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