开发者

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, openoff开发者_开发百科ice). 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?)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜