Python:解析 thorn 分隔文件 - 代码适用于 Windows,但不适用于 Linux?

Python: Parse thorn delimited file - code works on Windows, but not on Linux?

以下代码在 windows 7:

中运行良好
[30]  delim = b'\xc3\xbe'.decode() # 'þ'
[31]  reader = csv.reader(my_file, delimiter=delim)

但是它在我的 ec2 实例上使用 python 3.4 在 Amazon Linux 上失败,抛出错误:

SyntaxError: Non-UTF-8 code starting with '\xfe' in file data_loader.py on line 30, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

我是运行它来自linuxshell,即:

python3 data_loader.py

但是,当我在 ec2 linux 服务器上使用 Python 3.4 命令行时,我得到了预期的结果:

>>> b'\xc3\xbe'.decode()
'þ'

我试过为很多东西设置 delim,包括:

delim = '\xfe'

但我得到了同样的错误。

谁能帮我弄清楚这是怎么回事?就像我说的,代码在 Python 3.4、windows 7.

上运行良好

谢谢!

错误是由于第30行的注释中包含非ascii字符引起的

根据 PEP article,python 本身将您链接到:

This PEP proposes to introduce a syntax to declare the encoding of a Python source file. The encoding information is then used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.

...

Python will default to ASCII as standard encoding if no other encoding hints are given.

要修复您的错误,您可以从第 30 行删除注释,或者您可以指定一个文件编码,python 解释器将使用该文件编码来正确读取该注释。

例如,如果您在创建源文件时使用 latin-1 编码来添加 'þ' 字符,则将此行添加到 python 脚本的顶部:

# coding=latin-1

用文件的实际编码替换编码,您应该可以开始了。