使用 python 更新 csv 文件
我正在开发一个小项目,其中步骤之一是在 csv 文件上写入数据列表。 我正在循环遍历列表,获取特定数据并将其写入 csv。 问题是当处理写入操作时,它会删除 csv 文件的先前条目。我的 csv 写入方法如下: 和一个示例
def csv_writer(data_list,file_path):
import csv
file_p = open(file_path, "wb")
write_pattern = csv.writer(file_p, delimiter=",", quotechar=",")
write_pattern.writerow(data_list)
file_p.close()
示例数据列表是:
data_list = ['a', '', 'a', 'a', 'd', 'e']
我正在尝试在文件中包含数据,如下所示:
a,,a,d,e
a,b,c,d,e
a,g.j,l,m
提前致谢。
I am working on a small project,where one of the step is to write on a csv file a list of data.
I am looping through a list,and fetching specific data and writing it to a csv.
The problem is when the write operation is being processed it removes previous entries of the csv file.My csv writing method is as follows:
and an example
def csv_writer(data_list,file_path):
import csv
file_p = open(file_path, "wb")
write_pattern = csv.writer(file_p, delimiter=",", quotechar=",")
write_pattern.writerow(data_list)
file_p.close()
An example data list is:
data_list = ['a', '', 'a', 'a', 'd', 'e']
And I am trying to have data in the file as follows:
a,,a,d,e
a,b,c,d,e
a,g.j,l,m
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
也许以附加模式打开文件?
Maybe open the file in append mode?
当您打开文件时,尝试打开它进行附加,如下所示。
When you open the file, try opening it for appending, like this.
delimiter 和 quotechar 最好选择不同的
正如我理解的问题,目的是在 CSV 文件的所有内容之前插入一个新行。这是执行此操作的代码:
delimiter and quotechar must preferably be choosen as different
As I understood the question, the aim is to insert a new line before all the content of a CSV file. Here's the code to do that: