gpt4 book ai didi

python - 使用 Python 的 CSV 模块覆盖 csv 文件中的特定行

转载 作者:太空狗 更新时间:2023-10-29 22:04:27 24 4
gpt4 key购买 nike

我正在使用 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。

最佳答案

我将添加到 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)

关于python - 使用 Python 的 CSV 模块覆盖 csv 文件中的特定行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4148772/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com