使用 Python 的 CSV 模块覆盖 csv 文件中的特定行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4148772/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Overwriting a specific row in a csv file using Python's CSV module
提问by William Wallace
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? I've scoured Gogle and other stackoverflow posts to no avail. I assume my limited programming knowledge is to blame rather than Google.
在第二种情况下,我如何告诉 Python 我需要覆盖特定的行?我已经搜索了 Gogle 和其他 stackoverflow 帖子,但无济于事。我认为应该怪我有限的编程知识而不是谷歌。
采纳答案by mouad
I will add to StevenAnswer :
我会添加到史蒂文回答:
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)
回答by Steven Rumbalski
You cannot overwrite a single row in the CSV file. You'll have to write all the rows you want to a new file and then rename it back to the original file name.
您不能覆盖 CSV 文件中的一行。您必须将所需的所有行写入新文件,然后将其重命名为原始文件名。
Your pattern of usage may fit a database better than a CSV file. Look into the sqlite3 module for a lightweight database.
您的使用模式可能比 CSV 文件更适合数据库。查看 sqlite3 模块以获得轻量级数据库。

