[英]Overwriting a specific row in a csv file using Python's CSV module
I'm using Python's csv module to do some reading and writing of csv files.我正在使用 Python 的 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.我的阅读很好并附加到 csv 中,但我希望能够覆盖 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()
And I'm using basically the same for the overwrite mode(which isn't correct, it just overwrites the whole csv file):而且我使用的覆盖模式基本相同(这是不正确的,它只是覆盖了整个 csv 文件):
b=open('bottles.csv','wb')
writer = csv.writer(b)
writer.writerow([bottle,btlnum,100,img])
b.close()
In the second case, how do I tell Python I need a specific row overwritten?在第二种情况下,我如何告诉 Python 我需要覆盖特定的行? I've scoured Gogle and other stackoverflow posts to no avail.我已经搜索了 Gogle 和其他 stackoverflow 帖子,但无济于事。 I assume my limited programming knowledge is to blame rather than Google.我认为应该怪我有限的编程知识而不是谷歌。
I will add to Steven Answer :我会添加到史蒂文回答:
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)
You cannot overwrite a single row in the CSV file.您不能覆盖 CSV 文件中的一行。 You'll have to write all the rows you want to a new file and then rename it back to the original file name.您必须将所需的所有行写入新文件,然后将其重命名为原始文件名。
Your pattern of usage may fit a database better than a CSV file.您的使用模式可能比 CSV 文件更适合数据库。 Look into the sqlite3 module for a lightweight database.查看 sqlite3 模块以获得轻量级数据库。
我想使用python替换现有csv文件中的每个备用完整行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.