Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/328.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从文本文件读取时的Unicode编码_Python_Text_Unicode_Encoding_Utf 8 - Fatal编程技术网

Python 从文本文件读取时的Unicode编码

Python 从文本文件读取时的Unicode编码,python,text,unicode,encoding,utf-8,Python,Text,Unicode,Encoding,Utf 8,我希望你能帮忙 我试图获取一个字符串,并检查它是否位于名为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 =

我希望你能帮忙

我试图获取一个字符串,并检查它是否位于名为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”作为默认编码

我卡住了,我能做什么

使用模块打开文件:


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

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

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


将open('PasswordList.txt',emcoding='utf8')作为f:有效吗?我刚刚尝试将open('PasswordList.txt',encoding='utf8')作为f:有效,并将open('PasswordList.txt',encoding='utf-8')作为f:有效,但都没有成功,正在取得进展!现在,我得到一个不同的错误UnicodeDecodeError:“utf-8”编解码器无法解码位置0中的字节0x82:无效的起始字节文本文件中的第一个字符是F.\ux。正如我提到的,您需要知道文件的编码方式。我不能告诉你。您需要知道该文件是如何创建的。该文件是我使用记事本创建的.txt文件。我怎样才能知道它是用什么编码的?有没有一种简单的方法可以通过Python更改其编码?请尝试使用
'latin-1'
编码打开它。注意:只有在记事本中创建并保存文件时,这才有帮助。记事本不知道现有文件的编码
ANSI
表示您当地的8位代码页-在美国和西欧,这通常等同于
windows-1252
codec
import io
with io.open('PasswordList.txt', encoding='cp1252') as f:
    ...