美文网首页
python 读取文件、并以十六进制的方式写入到新文件

python 读取文件、并以十六进制的方式写入到新文件

作者: 还是那个没头脑 | 来源:发表于2021-08-26 14:49 被阅读0次

基本版本

# coding:utf-8
# 读取test.mp4,然后以16进制方式写到txt文件

infile = open("./stodownload.mp4", "rb")
outfile = open("out.txt", "w")
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
# 程序目标,读取test.mp4,然后以16进制方式写到txt文件

def main():
    f = open("./test.mp4", "rb")
    outfile = open("out.txt", "w")
    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
# 程序目标,读取test.mp4,然后以16进制方式写到txt文件
 
def main():
    f = open("./test.mp4", "rb")
    outfile = open("out.txt", "w")
    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()

使用 010 Editor 软件

相关文章

网友评论

      本文标题:python 读取文件、并以十六进制的方式写入到新文件

      本文链接:https://www.haomeiwen.com/subject/yohuiltx.html