简体   繁体   English

使用 python 更新 csv 文件

[英]updating on a csv file using python

I am working on a small project,where one of the step is to write on a csv file a list of data.我正在做一个小项目,其中一个步骤是在 csv 文件上写入数据列表。 I am looping through a list,and fetching specific data and writing it to a csv.我正在遍历一个列表,并获取特定数据并将其写入 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问题是在处理写入操作时,它会删除 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() 

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.提前致谢。

Maybe open the file in append mode?也许在 append 模式下打开文件?

file_p = open(file_path, "ab")

When you open the file, try opening it for appending, like this.当您打开文件时,请尝试打开它以进行附加,如下所示。

def csv_writer(data_list,file_path):
    import csv
    file_p = open(file_path, "a")
    write_pattern = csv.writer(file_p, delimiter=",", quotechar=",")
    write_pattern.writerow(data_list)
    file_p.close() 

delimiter and quotechar must preferably be choosen as different delimiterquotechar最好选择不同的

As I understood the question, the aim is to insert a new line before all the content of a CSV file.据我了解这个问题,目的是在 CSV 文件的所有内容之前插入一个新行。 Here's the code to do that:这是执行此操作的代码:

import csv

def csv_writer(data_list,file_path):
    file_p = open(file_path, "rb+")
    reader_pattern = csv.reader(file_p, delimiter=",", quotechar="$")
    write_pattern = csv.writer(file_p, delimiter=",", quotechar="$")

    content = list(reader_pattern)

    file_p.seek(0,0)
    write_pattern.writerow(data_list)
    write_pattern.writerows(content)
    file_p.truncate()
    file_p.close()


data_list = ['a', '', 'a', 'a', 'd', 'e']


csv_writer(data_list,'Copie de zozou.txt')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM