我正在尝试对文件进行简单解析,但由于特殊字符而出现错误:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
infile = 'finance.txt'
input = open(infile)
for line in input:
if line.startswith(u'▼'):
我得到错误:
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1718: ordinal not in range(128)
解决方案?
请您参考如下方法:
您需要提供编码。例如,如果它是 utf-8:
import io
with io.open(infile, encoding='utf-8') as fobj:
for line in fobj:
if line.startswith(u'▼'):
这适用于 Python 2 和 3。默认情况下,Python 2 打开文件时假定没有编码,即读取内容将返回字节字符串。因此,您只能读取 ascii 字符。在 Python 3 中默认是什么 locale.getpreferredencoding(False) 在许多情况下返回 utf-8。 Python 2 中的标准 open() 不允许指定编码。使用 io.open() 可以保证 future 的安全,因为您在切换到 Python 3 时无需更改代码。
在 Python 3 中:
>>> io.open is open
True
