Python:Parse thorn分隔的文件代码可以在Windows上运行,但在Linux上不行?

2024-09-28 18:47:17 发布

您现在位置:Python中文网/ 问答频道 /正文

以下代码在windows 7中运行良好:

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

但是,在我使用python3.4的ec2实例上,它在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

我在linux shell上运行它,即:

^{pr2}$

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

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

我试过让熟食店做很多事情,包括:

delim = '\xfe'

但我也犯了同样的错误。在

有人能帮我弄清楚发生了什么事吗?就像我说的,代码在Python3.4、Windows7上运行良好。在

谢谢!在


Tags: csv代码mylinuxwindows错误ec2reader
1条回答
网友
1楼 · 发布于 2024-09-28 18:47:17

错误是由于在第30行的注释中包含了一个非ascii字符造成的。在

根据python本身链接到的PEP article

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解释器用于正确读取注释的文件编码。在

例如,如果您在创建源文件时使用了拉丁语-1编码来添加'þ'字符,那么在python脚本的顶部添加以下行:

# coding=latin-1

用文件的实际编码替换编码,这样就可以开始了。在

相关问题 更多 >