简体   繁体   中英

How to create valid CSV file with DictWriter in Python?

I create CSV file with this code below:

dwf = open(file_name, 'w')
fw = csv.DictWriter(dwf, fieldnames=fields, delimiter='\t')
fw.writeheader()

data_dict = {'name':name, 'text': text, 'type':type 'URL': this_url}
fw.writerow(data_dict)

The 'text' field contains textual data, and when I created the 'text' variable, I did this:

text = text.strip().replace('\t', '  ').replace('\n', ' ').replace('\r', ' ')

I intended to remove any potential trouble maker that may be a column delimiter. But still, the csv file created is sometimes invalid, because when I opened it in Numbers on my Mac, some columns are in the same column, not alined with the delimiter.

How can I avoid this?

Try using the quoting parameter of csv.DictWriter to make sure that all of the fields are wrapped with quotes.

csv.DictWriter(dwf, fieldnames=fields, delimiter="\t", quoting=csv.QUOTE_ALL)

https://docs.python.org/3/library/csv.html#csv.QUOTE_ALL

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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