【问题标题】:Unicode encoding when reading from text file从文本文件读取时的 Unicode 编码
【发布时间】:2015-11-24 02:34:14
【问题描述】:

希望你能帮上忙。

我正在尝试获取一个字符串并检查它是否在名为 PasswordList 的文本文件中。这是我为此编写的代码:

Password = input('Enter a password: ')    
with open('PasswordList.txt') as f:
    Found = False
    for line in f:
        if Password in line: 
            print(line)
            Found = True
    if not Found:
        print('Password is not in list')

如果我输入类似字母“e”的内容,它将返回包含它的行,直到到达位置 4583 并返回错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0x82 in position 4853: ordinal not in range(128).

我猜这与 ascii 和 unicode 之间的编码有关,因为 Python 试图使用 ascii 编解码器来解码 unicode 字符?

如果我尝试

print (str((sys.getdefaultencoding())))

然后我得到“utf-8”作为默认编码。

我被卡住了,我该怎么办?

【问题讨论】:

  • 用 open('PasswordList.txt', emcoding='utf8') as f: 工作吗?
  • 我刚试过 open('PasswordList.txt', encoding='utf8') as f: 和 open('PasswordList.txt', encoding='utf-8') as f: 都没有工作

标签: python text unicode encoding utf-8


【解决方案1】:

使用io 模块打开文件:

import io
with io.open('PasswordList.txt', encoding='cp1252') as f:
    ...

但是,您确实需要知道数据的编码方式。文件本身通常不包含此信息,您必须知道它是如何创建的。

【讨论】:

  • 好的,取得进展!现在我得到一个不同的错误 UnicodeDecodeError: 'utf-8' codec can't decode byte 0x82 in position 0: invalid start byte
  • 文本文件中的第一个字符是 F ._.
  • 正如我提到的,你需要知道文件的编码是什么。我不能告诉你。您需要知道文件是如何创建的。
  • 该文件是我使用记事本创建的 .txt 文件。我怎么知道它是什么编码?有没有一种简单的方法可以通过 Python 更改其编码?
  • 尝试使用'latin-1' 编码打开它。
【解决方案2】:

要确定使用记事本创建的文件的编码,请在记事本中打开该文件。选择文件 |从菜单另存为。在对话框底部附近,当前编码显示在下拉列表中(附截图)。

现在您可以按照 wim 的建议尝试使用 codecs.open。

【讨论】:

  • 注意:这仅在您在记事本中创建和保存文件时才有帮助。记事本不知道现有文件的编码。 ANSI 表示您本地的 8 位代码页 - 在美国和西欧,这通常等同于 windows-1252 编解码器
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-22
相关资源
最近更新 更多