【问题标题】:UTF-8 is not working with Cyrillic alphabet in PycharmUTF-8 不适用于 Pycharm 中的西里尔字母
【发布时间】:2019-08-28 18:16:25
【问题描述】:

如果我在程序中做某事,它可以正常工作,但在我读取文件时它不起作用。

with open('test.txt', 'r') as f:

    print(f.read())

输入(文本.txt):

слово
строка

输出:

слово
строка

我将全局和项目编码都设置为 UTF-8。没有结果。

【问题讨论】:

  • text.txt 文件的编码是什么?如果那不是 UTF-8,那可能是你的麻烦。
  • @EiríkrÚtlendi UTF-8 不一定是默认值。 locale.getpreferredencoding(False) 是默认值。从输出中,我会说默认为cp1251,但文件编码为utf8

标签: windows-7 python encoding utf-8 pycharm


【解决方案1】:

文件以 UTF-8 编码,但您的区域设置默认为 cp1251。明确并始终使用其已知编码打开文件:

#!python3
with open('test.txt', encoding='utf8') as f:
    print(f.read())

Python 2 用户需要使用io 模块。 Python 2 内置的open 不支持encoding 参数。 io.open 是 Python 3 的实现,可用于 Python 2 和 Python 3 以实现可移植性。

此代码同时兼容 Python 2 和 3:

from __future__ import print_function # for Python 3 print syntax in Python 2.
import io
with io.open('test.txt', encoding='utf8') as f:
    print(f.read())

参考:open

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-04-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-04
    相关资源
    最近更新 更多