【发布时间】:2016-12-09 20:45:21
【问题描述】:
所以我有这个 csv,它有这样的行:
"41975","IT","Catania","2016-01-12T10:57:50+01:00",409.58
"538352","DE","Düsseldorf","2015-12-18T20:50:21+01:00",95.03
"V22211","GB","Nottingham","2015-12-31T11:17:59+00:00",872
在当前示例中,第一个和第三个单词工作正常,但程序在打印 Düsseldorf 时崩溃,ü 有问题
我希望能够从这个 csv 文件中获取信息并能够print 它。这是我的代码:
def load_sales(file_name):
SALES_ID = 0
SALES_COUNTRY = 1
SALES_CITY = 2
SALES_DATE = 3
SALES_PRICE =4
with open(file_name, 'r', newline='', encoding='utf8') as r:
reader = csv.reader(r)
result=[]
for row in reader:
sale={}
sale["id"]=row[SALES_ID]
sale["country"]=row[SALES_COUNTRY]
sale["city"]=row[SALES_CITY]
sale["date"]=row[SALES_DATE]
sale["price"]=float(row[SALES_PRICE])
result.append(sale)
当我打印时,我会打印 result 我得到:
File "C:\Anaconda3\lib\encodings\cp866.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_map)[0]
UnicodeEncodeError: 'charmap' codec can't encode character '\xfc' in position 384: character maps to <undefined>
到目前为止,我已经尝试过:用utf-8、UTF8等更改open函数中的encoding值,制作打印函数:
def write_uft8(data):
print(data).encode('utf-8')
但是当您必须打印字典列表时,这不是一种可行的方法。
有人告诉我,问题是我的 python 没有设置为将这些消息编码为 utf-8,这是真的吗?我该如何更改它?
【问题讨论】:
-
这可能是由于输入文件/数据的编码造成的。你确定数据是
utf-8吗?此外,您可以在此处找到所有编码的完整列表:docs.python.org/3.5/library/codecs.html#standard-encodings 我建议尝试iso-8859-1或使用chardet模块来尝试自动检测文件编码。 -
在示例集中,问题只出现在ü中的Düsseldorf这个词中,其他都很好
-
你的问题是你运行代码的windows cmd,不是因为python
-
我该如何解决?
-
在运行前尝试将代码页更改为 UTF8 ...
CHCP 65001
标签: python python-3.x csv encoding utf-8