【问题标题】:Python CSV, How to append data at the end of a row whilst reading it line by line (row by row)?Python CSV,如何在一行的末尾附加数据,同时逐行(逐行)读取它?
【发布时间】:2020-10-04 02:12:13
【问题描述】:

我正在读取一个名为: Candidates.csv line by line (row by row) 的 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

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

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

【问题讨论】:

    标签: python python-3.x csv file-writing


    【解决方案1】:

    在尝试之前备份您的文件以防万一。

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

    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)
    

    【讨论】:

    • 嗨 Faizan,我收到此错误: PermissionError: [WinError 32] 该进程无法访问该文件,因为它正被另一个进程使用:'C:\\Users\\COBRAC~1\ \AppData\\Local\\Temp\\tmpa5gh3d1j'
    • 确保shutil.movewith 块之外被调用。
    猜你喜欢
    • 1970-01-01
    • 2018-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多