Python,UnicodeDecodeError:'ascii'编解码器无法解码1718位的字节0xc2:序号不在范围内(128)

tri*_*tic 1 python string encoding python-2.7

我正在尝试简单解析文件并因特殊字符而得到错误:

#!/usr/bin/env python                                                                                                                 
# -*- coding: utf-8 -*-                                                                                                               

infile = 'finance.txt'
input = open(infile)
for line in input:
  if line.startswith(u'?'):
Run Code Online (Sandbox Code Playgroud)

我收到错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2 in position 1718: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

解?

Mik*_*ler 5

您需要提供编码.例如,如果它是utf-8:

import io

with io.open(infile, encoding='utf-8') as fobj:
    for line in fobj:
        if line.startswith(u'?'):
Run Code Online (Sandbox Code Playgroud)

这适用于Python 2和3.默认情况下,Python 2打开文件,假设没有编码,即读取内容将返回字节字符串.因此,您只能读取ascii字符.在Python 3中,默认情况下 locale.getpreferredencoding(False)返回的是许多情况utf-8.open()Python 2中的标准不允许指定编码.使用io.open()使它成为未来的证明,因为在切换到Python 3时不需要更改代码.

在Python 3中:

>>> io.open is open
True
Run Code Online (Sandbox Code Playgroud)