• 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("
    ")
            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("
    ")
            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()
    

    文件的数据变成了

  • 相关阅读:
    prim 堆优化+ kruskal 按秩优化
    poj 2679 Adventurous Driving(SPFA 负环)
    poj 1125 Stockbroker Grapevine (dij优化 0ms)
    codevs 4909 寂寞的堆(写的好丑0.0)
    noi 7221 拯救公主 (状态压缩+bfs)
    codevs2059逃出克隆岛(传送门bfs)
    HUD3336
    poj 3974 Palindrome
    疑难杂症
    正则表达 比较两个浮点数
  • 原文地址:https://www.cnblogs.com/tk091/p/3410245.html
Copyright © 2020-2023  润新知