Python CSV:从值中删除引号
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4753704/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python CSV: Remove quotes from value
提问by neolaser
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
我有一个可以下载、编辑然后再次上传 CSV 文件的过程。下载时,CSV 文件格式正确,没有双引号
1, someval, someval2
When I open the CSV in a spreadsheet, edit and save, it adds double quotes around the strings
当我在电子表格中打开 CSV,编辑并保存时,它会在字符串周围添加双引号
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.
我认为这只是电子表格的操作(在本例中为 openoffice)。我希望我的上传脚本删除包装双引号。我无法删除所有引号,只是为了防止正文包含它们,而且我也不想只检查双引号的第一个和最后一个字符。
Im almost sure that the CSV library in python would know how to handle this, but not sure how to use it...
我几乎可以肯定 python 中的 CSV 库知道如何处理这个问题,但不确定如何使用它...
EDIT When I use the values within a dictionary, they turn out as follows
编辑当我使用字典中的值时,结果如下
{'header':'"value"'}
Thanks
谢谢
采纳答案by Sven Marnach
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 csvmodule.
回答by neolaser
Thanks to everyone who was trying to help me, but I figured it out. When specifying the reader, you can define the quotechar
感谢所有试图帮助我的人,但我想通了。指定reader时,可以定义quotechar
csv.reader(upload_file, delimiter=',', quotechar='"')
This handles the wrapping quotes of strings.
这处理字符串的包装引号。
回答by Yuchen Zhong
For Python 3:
对于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
原始答案在 Python 3 下给出了此错误。另请参阅此 SO 以获取详细信息: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?)
回溯(最近一次调用):文件“remove_quotes.py”,第 11 行,在 writer.writerows(reader) _csv.Error:迭代器应该返回字符串,而不是字节(您是否以文本模式打开文件?)

