简体   繁体   English

File to Hex to File in python 2.7

[英]File to Hex to File in python 2.7

I'm trying to take a file and convert it's contents to hex, save that to a file, and then convert the hex string back to ascii and save that to a file. 我正在尝试获取一个文件并将其内容转换为十六进制,将其保存到文件中,然后将十六进制字符串转换回ascii并将其保存到文件中。 The below method works, but adds an extra empty line after ever line in the hex to ascii file, which should be identical to the initial file... 下面的方法有效,但是在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()

================================================================================== ================================================== ================================

After actually reading the python documentation, I realized my mistake. 在实际阅读python文档之后,我意识到了自己的错误。 The code should be as follows. 代码应如下。 (Slightly altered to read from the out.txt...) (稍作更改以从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()

The key was adding the appending "b" to the the "w" in the open command to have the file opened in binary write mode... 关键是在open命令的“ w”后面添加“ b”,以二进制写入模式打开文件。

Rather than using str.decode , you should try using binascii.unhexlify . 而不是使用str.decode ,您应该尝试使用binascii.unhexlify decode might be doing the translation of line-breaks slightly differently, eg how it handles '\\r\\n' vs '\\n' . decode可能在换行符转换方面稍有不同,例如,它如何处理'\\r\\n''\\n'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM