Reputation: 7683
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?
Upvotes: 0
Views: 99
Reputation: 15128
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
Upvotes: 1