在 Python 中覆盖 CSV 中的列

Overwriting a column in CSV in Python

我正在尝试覆盖 CSV 中的列,但无法做到这一点。

import os 
import csv
r=len(list(csv.reader(open('C:/Users/KaanPISI/Desktop/seyiresas.csv'))))

open('C:/Users/KaanPISI/Desktop/seyiresas.csv','w')
for i in range(0,r):

       row[i] = row[i].write('/home/nvidia/racecar-ws/src/racecar-
       controllers/deep_learning/data/057/',"%05d"%i,'.jpg')
       i=i+1

这最终删除了 CSV 中的所有内容。

您为打开的文件使用了错误的模式。如您所见here

(...)'w' for only writing (an existing file with the same name will be erased), and 'a' opens the file for appending(...)

因此,当您设置 w 标志时,您会覆盖您的文件。您需要做的就是在这一行

上将 w 更改为 a
open('C:/Users/KaanPISI/Desktop/seyiresas.csv','w')

不幸的是,我还没有找到使用 csv 模块覆盖 CSV 中特定行的方法;你必须用你的新数据写一个新文件(或覆盖现有文件,如下所示)。

在下面的代码中,我将 CSV 读入行列表 (lines),然后您可以根据需要修改每个元素,然后删除 CSV 并使用lines 中的相同名称和修改后的数据。我正在使用 with() 运算符,因为 close() 是自动完成的。

import os
import csv

filepathIn = 'PATH TO YOUR CSV'

# First read the contents of your current file
with open(filepathIn,'r') as f:
    lines = f.readlines()

## lines is now a list of each row in the CSV. Modify as needed

# Remove the file and write a new one of the same name
os.remove(filepathIn)
with open(filepathIn,'w',newline='') as output:
    write = csv.writer(output)
    write.writerows(lines)