【发布时间】: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