使用Python';覆盖csv文件中的特定行;s CSV模块

使用Python';覆盖csv文件中的特定行;s CSV模块,python,csv,Python,Csv,我正在使用Python的csv模块来读写csv文件 我有阅读罚款和附加到csv罚款,但我想能够覆盖csv中的特定行 作为参考,以下是我的阅读和编写代码以附加: #reading b = open("bottles.csv", "rb") bottles = csv.reader(b) bottle_list = [] bottle_list.extend(bottles) b.close() #appending b=open('

我正在使用Python的csv模块来读写csv文件

我有阅读罚款和附加到csv罚款,但我想能够覆盖csv中的特定行

作为参考,以下是我的阅读和编写代码以附加:

    #reading
    b = open("bottles.csv", "rb")
    bottles = csv.reader(b)
    bottle_list = []
    bottle_list.extend(bottles)
    b.close()

    #appending
    b=open('bottles.csv','a')
    writer = csv.writer(b)
    writer.writerow([bottle,emptyButtonCount,100, img])
    b.close()
我使用的覆盖模式基本相同(这是不正确的,它只是覆盖了整个csv文件):


在第二种情况下,如何告诉Python我需要覆盖特定的行?我搜遍了Gogle和其他stackoverflow的帖子都没有用。我认为是我有限的编程知识造成的,而不是谷歌。

你不能覆盖CSV文件中的一行。您必须将所有需要的行写入新文件,然后将其重命名回原始文件名

您的使用模式可能比CSV文件更适合数据库。查看sqlite3模块中的轻量级数据库。

我将添加以下内容来回答:


谢谢你的提示!我现在正在查看sqlite3文档。如果我有更多的数据,我可能会使用它。现在singularity的解决方案很好,因为我的csv文件不太大。
    b=open('bottles.csv','wb')
    writer = csv.writer(b)
    writer.writerow([bottle,btlnum,100,img])
    b.close()
import csv

bottle_list = []

# Read all data from the csv file.
with open('a.csv', 'rb') as b:
    bottles = csv.reader(b)
    bottle_list.extend(bottles)

# data to override in the format {line_num_to_override:data_to_write}. 
line_to_override = {1:['e', 'c', 'd'] }

# Write data to the csv file and replace the lines in the line_to_override dict.
with open('a.csv', 'wb') as b:
    writer = csv.writer(b)
    for line, row in enumerate(bottle_list):
         data = line_to_override.get(line, row)
         writer.writerow(data)