简体   繁体   中英

Python CSV: Remove quotes from value

I have a process where a CSV file can be downloaded, edited then uploaded again. On the download, the CSV file is in the correct format, with no wrapping double quotes

1, someval, someval2

When I open the CSV in a spreadsheet, edit and save, it adds double quotes around the strings

1, "someEditVal", "someval2"

I figured this was just the action of the spreadsheet (in this case, openoffice). I want my upload script to remove the wrapping double quotes. I cannot remove all quotes, just incase the body contains them, and I also dont want to just check first and last characters for double quotes.

Im almost sure that the CSV library in python would know how to handle this, but not sure how to use it...

EDIT When I use the values within a dictionary, they turn out as follows

{'header':'"value"'}

Thanks

For you example, the following works:

import csv
writer = csv.writer(open("out.csv", "wb"), quoting=csv.QUOTE_NONE)
reader = csv.reader(open("in.csv", "rb"), skipinitialspace=True)
writer.writerows(reader)

You might need to play with the dialect options of the CSV reader and writer -- see the documentation of the csv module .

Thanks to everyone who was trying to help me, but I figured it out. When specifying the reader, you can define the quotechar

csv.reader(upload_file, delimiter=',', quotechar='"')

This handles the wrapping quotes of strings.

For Python 3 :

import csv
writer = csv.writer(open("query_result.csv", "wt"), quoting=csv.QUOTE_NONE, escapechar='\\')
reader = csv.reader(open("out.txt", "rt"), skipinitialspace=True)
writer.writerows(reader)

The original answer gives this error under Python 3. Also See this SO for detail: csv.Error: iterator should return strings, not bytes

Traceback (most recent call last): File "remove_quotes.py", line 11, in writer.writerows(reader) _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

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