python 讀取文件、並以十六進制的方式寫入到新文件


#!/usr/bin/env python
infile = file("in.mp3","rb")
outfile = file("out.txt","wb")
def main():
    while 1:
        c = infile.read(1)
        if not c:
            break
        outfile.write(hex(ord(c)))
    outfile.close()
    infile.close()
if __name__ == '__main__':
    main()

下面是我自己改過的

#coding:utf-8
# 程序目標,讀取1.bmp,然后以16進制方式寫到txt文件

def main():
    f = open("1.bmp","rb")
    outfile = open("out.txt","wb")
    i = 0
    while 1:
        c = f.read(1)
        i = i + 1
        if not c:
            break
        if i%32 == 0:
            outfile.write("\n")
        else:
            if ord(c) <= 15:
                outfile.write("0x0"+hex(ord(c))[2:]+" ")
            else:
                outfile.write(hex(ord(c))+" ")
    outfile.close()
    f.close()
		
if __name__=="__main__":
    main()

 

效果如下:

 

當然,我需要的是真正的十六進制值。然后代碼變成了這樣

#coding:utf-8
# 程序目標,讀取1.bmp,然后以16進制方式寫到txt文件

def main():
    f = open("1.bmp","rb")
    outfile = open("out.txt","wb")
    i = 0
    while 1:
        c = f.read(1)
        i = i + 1
        if not c:
            break
        if i%32 == 0:
            outfile.write("\n")
        else:
            if ord(c) <= 15:
                outfile.write(("0x0"+hex(ord(c))[2:])[2:]+" ")
            else:
                outfile.write((hex(ord(c)))[2:]+" ")
    outfile.close()
    f.close()
		
if __name__=="__main__":
    main()

文件的數據變成了


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM