【问题标题】:Overwriting a specific row in a csv file using Python's CSV module使用 Python 的 CSV 模块覆盖 csv 文件中的特定行
【发布时间】:2010-11-10 20:30:23
【问题描述】:

我正在使用 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 文件):

    b=open('bottles.csv','wb')
    writer = csv.writer(b)
    writer.writerow([bottle,btlnum,100,img])
    b.close()

在第二种情况下,我如何告诉 Python 我需要覆盖特定的行?我搜索了 Gogle 和其他 stackoverflow 帖子,但无济于事。我认为应该归咎于我有限的编程知识而不是 Google。

【问题讨论】:

    标签: python csv


    【解决方案1】:

    我会添加到Steven 答案:

    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)
    

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 感谢您的提示!我现在正在研究 sqlite3 文档。如果我有更多数据要扔掉,我可能会使用它。现在奇点的解决方案很好,因为我的 csv 文件不是太大。
      猜你喜欢
      • 2013-05-20
      • 1970-01-01
      • 1970-01-01
      • 2013-05-06
      • 2016-03-02
      • 2017-12-07
      相关资源
      最近更新 更多