[英]Detecting empty string when decoding byte array into unicode? (Python)
[英]Python Unicode Byte Decoding From File
我觉得这绝对是个白痴...
因此,我正在制作一个文件解密器,它可以读取文本文件,然后将其输出为加密文件,然后允许您将该文件转换回纯文本格式。 我已经将文件记下来了,但是读取它是个问题。
从加密:
newf.write(bytes(result[0], "utf-8"))
newf.write(bytes('{[:|:;:|:]}'))
newf.write(bytes(result[1], "utf-8"))
newf.close()
还有解密:
name = fudder.askopenfilename(defaultextension =("Text Files","*.txt"),title = "Choose a file to decrypt.")
with open(name,'rb') as Usefile:
filecont = bytes(Usefile.read(),'utf-8')
出现此错误:
File "C:\STUFF\FILE.py", line 93, in <lambda>
self.fileO = Button(text = 'Decrypt File', command = lambda: cryptFile())
File "C:\STUFF\FILE.py", line 60, in cryptFile
filecont = Usefile.read()
File "C:\Program Files (x86)\Python35-32\lib\encodings\cp1252.py", line 23, in decode
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
UnicodeDecodeError: 'charmap' codec can't decode byte 0x81 in position 68: character maps to <undefined>
追溯显示,在您的实际代码中,此行的cryptFile
函数中发生错误:
filecont = UseFile.read()
UnicodeDecodeError
表示UseFile
是一个类似文件的对象,可能已在文本模式下打开而未指定编码。 这意味着它将尝试使用cp1252的默认编码(在Windows上)对实际上已编码为UTF-8的文件进行解码。 显然,当编解码器遇到任何未映射的字节(例如0x81
)时,此操作将失败。
解决方案是在打开文件时指定正确的编码:
with open(name, 'rt', encoding='utf-8') as Usefile:
filecont = UseFile.read()
这将导致filecont
是一个unicode字符串对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.