使用Python 2.7读取和写入CSV文件,包括unicode

使用Python 2.7读取和写入CSV文件,包括unicode

我是Python新手,我有一个关于如何使用Python来读写CSV文件的问题。我的文件包含德语,法语等。根据我的代码,可以在Python中正确读取文件,但是当我将其写入新的CSV文件时,unicode会变成一些奇怪的字符。

我的代码是:

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()

你能告诉我应该怎样做才能解决这个问题吗?非常感谢你!


不负相思意
浏览 1463回答 3
3回答

慕姐4208626

确保您根据需要进行编码和解码。此示例将utf-8中的一些示例文本往返到csv文件并返回以演示:# -*- coding: utf-8 -*-import csvtests={'German': [u'Straße',u'auslösen',u'zerstören'],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;'French': [u'français',u'américaine',u'épais'],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;'Chinese': [u'中國的',u'英語',u'美國人']}with open('/tmp/utf.csv','w') as fout:&nbsp; &nbsp; writer=csv.writer(fout)&nbsp; &nbsp;&nbsp;&nbsp; &nbsp; writer.writerows([tests.keys()])&nbsp; &nbsp; for row in zip(*tests.values()):&nbsp; &nbsp; &nbsp; &nbsp; row=[s.encode('utf-8') for s in row]&nbsp; &nbsp; &nbsp; &nbsp; writer.writerows([row])with open('/tmp/utf.csv','r') as fin:&nbsp; &nbsp; reader=csv.reader(fin)&nbsp; &nbsp; for row in reader:&nbsp; &nbsp; &nbsp; &nbsp; temp=list(row)&nbsp; &nbsp; &nbsp; &nbsp; fmt=u'{:<15}'*len(temp)&nbsp; &nbsp; &nbsp; &nbsp; print fmt.format(*[s.decode('utf-8') for s in temp])打印:German&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Chinese&nbsp; &nbsp; &nbsp; &nbsp; French&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Straße&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;中國的&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; français&nbsp; &nbsp; &nbsp; &nbsp;auslösen&nbsp; &nbsp; &nbsp; &nbsp;英語&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;américaine&nbsp; &nbsp; &nbsp;zerstören&nbsp; &nbsp; &nbsp; 美國人&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; épais&nbsp;&nbsp;
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python