【问题标题】:UnicodeDecodeError Ordinal not in range, while reading line from fileUnicodeDecodeError 序数不在范围内,同时从文件中读取行
【发布时间】:2018-06-28 21:43:09
【问题描述】:

我在 Ubuntu (Jessie) 上运行 Python3。并重构了一些原本用Python2.7编写的代码。

我有一个 UTF-8 Unicode 文本文件...

$ file /home/(smip)/hg19.json
/home/(smip)/hg19.json: UTF-8 Unicode text

在旧代码中有...

#!/usr/bin/env python3
# -*- coding: utf-8
(...snip...)
with open(filename) as fh:
    return json.load(fh)

这会在尝试打开文件时导致错误...

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 510: ordinal not in range(128)

像这样更改代码以指定 utf-8 ...

with open(filename, "r", encoding="utf-8") as fh:
    return json.load(fh)

...修复该错误

所以我的问题是:

  1. 不应该 Python 3 能够在没有 encoding="utf-8" 的情况下打开 unicode 文件,这要归功于 shebang?
  2. 如果没有,为什么不呢?

【问题讨论】:

    标签: python-3.x file binary refactoring


    【解决方案1】:
    1. coding: utf-8 注释是源代码文件的encoding declaration。 Python 3 的默认值为 UTF-8。
    2. open() 使用的默认编码取决于locale

    如果您想让用户决定编码,您可以在外部设置LC_ALL=en_US.utf-8,或者在打开数据时将其显式设置为utf-8

    【讨论】:

      猜你喜欢
      • 2018-02-07
      • 2011-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多