使用Python的CSV模块覆盖csv文件中的特定行 [英] Overwriting a specific row in a csv file using Python's CSV module
问题描述
我使用Python的csv模块来做一些csv文件的读写。
I'm using Python's csv module to do some reading and writing of csv files.
我已经读取了罚款并附加到csv罚款,但我想要能够覆盖csv中的特定行。
I've got the reading fine and appending to the csv fine, but I want to be able to overwrite a specific row in the csv.
为了参考,这里是我的阅读,然后写入代码:
For reference, here's my reading and then writing code to append:
#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文件):
And I'm using basically the same for the overwrite mode(which isn't correct, it just overwrites the whole csv file):
b=open('bottles.csv','wb')
writer = csv.writer(b)
writer.writerow([bottle,btlnum,100,img])
b.close()
在第二种情况下,如何告诉Python I需要覆盖特定的行吗?我已经淘汰Gogle和其他stackoverflow帖子无济于事。
In the second case, how do I tell Python I need a specific row overwritten? I've scoured Gogle and other stackoverflow posts to no avail. I assume my limited programming knowledge is to blame rather than Google.
推荐答案
我将添加到老年人答案:
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的CSV模块覆盖csv文件中的特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!