【发布时间】: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)
...修复该错误
所以我的问题是:
- 不应该 Python 3 能够在没有 encoding="utf-8" 的情况下打开 unicode 文件,这要归功于 shebang?
- 如果没有,为什么不呢?
【问题讨论】:
标签: python-3.x file binary refactoring