我正在尝试获取文件并将其内容转换为十六进制,将其保存到文件中,然后将十六进制字符串转换回 ascii 并将其保存到文件中。下面的方法有效,但在十六进制的每一行之后添加一个额外的空行到 ascii 文件,这应该与初始文件相同......
import binascii
filename = 'file.txt'
with open(filename, 'rb') as f:
content = f.read()
out = binascii.hexlify(content)
f = open('out.txt', 'w')
f.write(out)
f.close()
asci = out.decode("hex")
w = open('printed.txt', 'w')
w.write(asci)
w.close()
==================================================== =================================
在实际阅读了python文档之后,我意识到了我的错误。代码应如下所示。(稍微修改为从 out.txt 中读取...)
import binascii
filename = 'file.txt'
with open(filename, 'rb') as f:
content = f.read()
out = binascii.hexlify(content)
f = open('out.txt', 'wb')
f.write(out)
f.close()
import binascii
filename = 'out.txt'
with open(filename, 'rb') as f:
content = f.read()
asci = content.decode("hex")
asci = out.decode("hex")
w = open('printed.txt', 'wb')
w.write(asci)
w.close()
关键是将附加的“b”添加到打开命令中的“w”中,以二进制写入模式打开文件......