0

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",""

3 Answers 3

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I had tried that one too. but it gives an error, _csv.Error: need to escape, but no escapechar set
1

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.

Comments

0

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', '']]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.