首页 > 解决方案 > 读取文件的特定位置并将其写入python中的新文件

问题描述

假设我有一个字节字符串文件,如下所示:

00101000000000011000000000000011001.......

我想读取二进制文件的每 8 位并将其写入一个新文件。我如何在python中做到这一点?

标签: python

解决方案


endianness = 'big'

with open('from.txt', 'rb') as r:
    with open('to.txt', 'wb') as w:
        while True:
            chars = r.read(8)
            if len(chars) == 8:
                string = ''.join([str(byte % 2) for byte in chars])
                if endianness == 'little':
                    string = string[::-1]
                byte = int(string, 2).to_bytes(1, endianness)
                w.write(byte)
            else:
                break

推荐阅读