【问题标题】:Overwriting a column in CSV in Python在 Python 中覆盖 CSV 中的列
【发布时间】:2018-06-29 16:05:41
【问题描述】:

我正在尝试覆盖 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 中的所有内容。

【问题讨论】:

标签: python csv overwrite


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

    (...)'w' 仅用于写入(已存在的同名文件将被擦除),'a' 打开文件以进行追加(...)

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

    open('C:/Users/KaanPISI/Desktop/seyiresas.csv','w')
    

    【讨论】:

    • 非常感谢,现在一切正常。但是 row[] 数组现在不起作用。我怎样才能让它打印到唯一的第一列?我怎样才能使这段代码工作?
    • “追加”模式只会追加到末尾,因此您将无法索引要覆盖的行
    猜你喜欢
    • 2014-01-10
    • 1970-01-01
    • 2018-08-27
    • 2013-05-20
    • 1970-01-01
    • 2021-06-30
    • 2019-11-14
    • 2012-02-01
    • 1970-01-01
    相关资源
    最近更新 更多