在Python中覆盖CSV中的列

2024-10-02 14:22:26 发布

您现在位置: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中的所有内容。在


Tags: csvimportforlenosopenuserslist
2条回答

不幸的是,我还没有找到使用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)

您对打开的文件使用了错误的模式。你可以读到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')

相关问题 更多 >