簡體   English   中英

File to Hex to File in python 2.7

[英]File to Hex to File in python 2.7

我正在嘗試獲取一個文件並將其內容轉換為十六進制,將其保存到文件中,然后將十六進制字符串轉換回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()

關鍵是在open命令的“ w”后面添加“ b”,以二進制寫入模式打開文件。

而不是使用str.decode ,您應該嘗試使用binascii.unhexlify decode可能在換行符轉換方面稍有不同,例如,它如何處理'\\r\\n''\\n'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM