List contains below data,
['Obama', 'John Barta', 'IN, 33, 33', '444', '']
I am trying to write this data into a csv file using below code,
with open(output_file, 'w') as writeFile:
writer = csv.writer(writeFile, delimiter=',', quotechar="'", quoting=csv.QUOTE_NONE)
writer.writerow(colValues)
But getting below output in csv file,
"Obama","John Barta",'"IN, 33, 33"',"444",""
I don't want single quote between '"IN, 33, 33"'.
Desired output:
"Obama","John Barta","IN, 33, 33","444",""
If you eliminate the quotechar
argument from the csv.writer
call, it should give you the desired behavior. For example, your function call would become
writer = csv.writer(writeFile, delimiter=',', quoting=csv.QUOTE_NONE)
The quotechar
argument is what is placed when the delimiter
or some other special character is present.
From your sample output, it looks like you want to quote all fields. So the straightforward way to do it would be with:
writer = csv.writer(writeFile, delimiter=',',
quotechar='"', quoting=csv.QUOTE_ALL)
I also changed quotechar
to be a double quote, since that's in your sample output also.
Maybe this is too simple, but with defaults write, read returns the original list:
import csv
col_values = ['Obama', 'John Barta', 'IN, 33, 33', '444', '']
with open('data.csv', 'w') as writeFile:
writer = csv.writer(writeFile)
writer.writerow(col_values)
#=> Obama,John Barta,"IN, 33, 33",444,
with open('data.csv', 'r') as f:
reader = csv.reader(f)
p_list = list(reader)
print(p_list)
#=> [['Obama', 'John Barta', 'IN, 33, 33', '444', '']]
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.