我想用Python写一个字符串到一个文件中。我知道怎么做,所以这不是问题。我也希望在这个字符串被写下来之后对它进行编码。编码并不重要,所以我还是选择UTF-32。我要做的是在我写了字符串之后,我再次从文件中读取,将字符串编码成字节,然后重新写入同一个文件。我可以做编码部分,但我的问题是解码。我想以字节的形式读取它,以便将其转换回str
。我所做的是相同的原则:从文件中读取、解码和写入同一个文件。我从读取编码字符串得到的结果看起来像b'\xff\xfe\x00\x001\x00\x00\x004\x00\x00\x002\x00\x00\x00'
当我以字节的形式读取它时,它将b
和反斜杠加倍。如果我像这样读它,作为一个字符串,然后尝试解码,它一直在说'str' object does not have attribute decode
或其他什么。我知道我不能解码字符串,但如果我尝试用字节,它似乎是“加倍”字节。
这是我的代码:
def readfile(filename):
f = open(filename, 'r')
s = f.read()
f.close()
return s
def readfile_b(filename):
f = open(filename, 'rb')
s = f.read()
f.close()
return s
def writefile(filename, writeobject):
f = open(filename, 'w')
f.write(writeobject)
f.close()
def encode(filename):
s = readfile(filename)
s_enc = bytes(s, 'utf-32')
writefile(filename, str(s_enc))
def decode(filename):
s_enc = readfile_b(filename)
print(s_enc)
s = str(s_enc, 'utf-32')
writefile(filename, s)
encode("Example.txt")
decode("Example.txt")
输出(对于decode(),encode()没有任何错误):
^{pr2}$非常感谢任何帮助
尝试在二进制写入中使用writefile。当前,您正在将转换为字符串的字节写入。当你读回去的时候你会得到b或2分。在
这对我有用:
相关问题 更多 >
编程相关推荐