我已将这种格式的 unicode 字符串保存在文本文件中 b'\x1e\x80E\xd7\xd4M\x94\xa8\xb4\xf3bl[^' 但是当我从这个外部文本文件中读取它时,它会被读取为普通字符串。
我尝试以二进制形式读取文件,例如 打开(celesi_file_path,“rb”)
fciphertext = open(ciphertext_file_path, "rb")
fkey = open(celesi_file_path,"rb")
celesi = fkey.read()
ciphertext = fciphertext.read()
ciphertext = ciphertext.decode('latin-1')
celesi = celesi.decode('latin-1')
print(type(celesi))
print(type(ciphertext))
print(celesi)
print(ciphertext)
输出是一个字符串,如下所示: “b'\x1e\x80E\xd7\xd4M\x94\xa8\xb4\xf3bl[^'” 虽然我期望它是一串不符合这种格式的字符
最佳答案
看看这个:
>>> data = b'\xd0\x9f\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82'
>>> str(data)
"b'\\xd0\\x9f\\xd1\\x80\\xd0\\xb8\\xd0\\xb2\\xd0\\xb5\\xd1\\x82'"
因此,如果您将 str(data)
写入文件,则实际上是写了斜杠和 x
。您没有编写字节,而是编写了Python 提供的这些字节的表示 字符串。在本例中,您写入了51 字节 (!),而不是原来的 12 个字节。
您应该自己编写字节:
with open("data.bin", "wb") as f:
f.write(data)
然后也以二进制模式打开该文件并读取字节。
关于python - unicode 不被解释为 Python 中的 unicode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54278958/