问题描述
我是 Python 新手,我有一个关于如何使用 Python 读写 CSV 文件的问题.我的文件包含德文、法文等.根据我的代码,Python 可以正确读取文件,但是当我将其写入新的 CSV 文件时,unicode 变成了一些奇怪的字符.
数据如下:
我的代码是:
导入csvf=open('xxx.csv','rb')读者= csv.reader(f)wt=open('llll.csv','wb')writer=csv.writer(wt,quoting=csv.QUOTE_ALL)wt.close()f.close()
结果如下:
我应该怎么做才能解决问题?
另一种选择:
使用 unicodecsv 包中的代码...
https://pypi.python.org/pypi/unicodecsv/
>>>将 unicodecsv 导入为 csv>>>从 io 导入 BytesIO>>>f = BytesIO()>>>w = csv.writer(f, encoding='utf-8')>>>_ = w.writerow((u'é', u'ñ'))>>>_ = f.seek(0)>>>r = csv.reader(f, encoding='utf-8')>>>next(r) == [u'é', u'ñ']真的该模块与 STDLIB csv 模块的 API 兼容.
I am new to Python, and I have a question about how to use Python to read and write CSV files. My file contains like Germany, French, etc. According to my code, the files can be read correctly in Python, but when I write it into a new CSV file, the unicode becomes some strange characters.
The data is like:
And my code is:
import csv
f=open('xxx.csv','rb')
reader=csv.reader(f)
wt=open('lll.csv','wb')
writer=csv.writer(wt,quoting=csv.QUOTE_ALL)
wt.close()
f.close()
And the result is like:
What should I do to solve the problem?
Another alternative:
Use the code from the unicodecsv package ...
https://pypi.python.org/pypi/unicodecsv/
>>> import unicodecsv as csv
>>> from io import BytesIO
>>> f = BytesIO()
>>> w = csv.writer(f, encoding='utf-8')
>>> _ = w.writerow((u'é', u'ñ'))
>>> _ = f.seek(0)
>>> r = csv.reader(f, encoding='utf-8')
>>> next(r) == [u'é', u'ñ']
True
This module is API compatible with the STDLIB csv module.
这篇关于使用 Python 2.7 读取和写入包含 unicode 的 CSV 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!