python - unicode 不被解释为 Python 中的 unicode

标签 python

我已将这种格式的 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/

相关文章:

python - 我如何从 __init__ 调用属性 setter

python - 是否可以进一步优化此数字运算算法?

python - 如何让 python 代码在时间 y 和 z 之间每隔 x 分钟循环一次?

python - 环境只能包含字符串 - wagtail CMS、Django

python - ATpy 导入错误 : No module named astropy. io

python - Python根据文件名的数值对文件进行排序

python - 如何在 `DataFrame.to_json` 期间获得 float 的精确表示?

python - 使用pylab生成热图

python - 缺少 Gensim doc2vec infer_vector 方法

python - 从列表列表中删除整个列表