【问题标题】:SyntaxError: Non-ASCII character '\xfe' in file error happenSyntaxError:发生文件错误中的非 ASCII 字符“\xfe”
【发布时间】:2017-07-27 02:36:47
【问题描述】:

SyntaxError: 发生文件错误中的非 ASCII 字符 '\xfe'。 我想读取 tsv 文件,并更改为 csv 文件。当我运行此应用程序时,会发生此错误。 我写了

# coding: shift_jis

import libraries as libraries
import DataCleaning
import csv


media = 'Google'
tsv = csv.reader(file(r"data/aaa.csv"), delimiter = '\t',encoding='UTF-16')

for row in tsv:
  print ", ".join(row)

我认为 ASCII 是错误的,但我不知道如何解决这个问题。 我的 tsv 文件是 shift_jis,最后我想将其更改为 UTF-8。但我认为发生此错误是因为我没有将编码指定为 UTF-16。

【问题讨论】:

    标签: python csv python-2.x


    【解决方案1】:

    Python 2 上的 csv 模块对 Unicode 不友好。您不能将encoding 作为参数传递给它,它不是可识别的参数(仅csv 格式参数被接受为关键字参数)。它不能正确使用 Py2 unicode 类型,因此使用它涉及以二进制模式读取,即使那样,它也只能在换行符每个字符一个字节时才能正常工作。每the csv module docs

    注意:此版本的 csv 模块不支持 Unicode 输入。此外,目前还有一些关于 ASCII NUL 字符的问题。因此,为了安全起见,所有输入都应该是 UTF-8 或可打印的 ASCII;请参阅示例部分中的示例。

    如果可能,切换到 Python 3,其中 csv 模块默认与 Py3 的 Unicode 友好的 str 一起使用,绕过 Python 2 的 csv 模块的所有问题,并且可以通过 encoding open 正确。在这种情况下,您的代码将简化为:

    with open(r"data/aaa.csv", encoding='utf-16', newline='') as inf:
        tsv = csv.reader(inf, delimiter='\t')
        # Explicit encoding argument may be needed for TextIOWrapper;
        # the rewrapping is done to ensure newline='' is used as the csv module requires
        csv.writer(io.TextIOWrapper(sys.stdout.buffer, newline='')).writerows(tsv)
    

    或以 CSV 格式写入 UTF-8 编码文件:

    with open(r"data/aaa.csv", encoding='utf-16', newline='') as inf, open(outfilename, "w", encoding='utf-8', newline='') as outf:
        tsv = csv.reader(inf, delimiter='\t')
        csv.writer(outf).writerows(tsv)
    

    如果失败,请查看the unicodecsv module on PyPI,它应该在 Python 2 上正确处理 Unicode 输入。

    【讨论】:

    • 谢谢你的 cmets。我把我的 python 改成了 3.6 版本。我写了你的代码(你的第二个代码)。我得到一个错误,NameError: name 'f' is not defined。在我的代码中,在f变量的部分,未解析的引用'f'和在io变量的部分,未解析的引用'io'。
    • 我应该怎么做才能修复它?
    • @user7664633: f 是我的错字(我将文件对象命名为inf 并偶然使用了f)。 io 是标准模块;将其导入文件顶部。
    猜你喜欢
    • 2014-10-01
    • 2012-10-24
    • 1970-01-01
    • 2013-08-07
    • 2023-03-09
    • 2014-12-06
    • 1970-01-01
    相关资源
    最近更新 更多