python - 读取文件的特定位置并将其写入python中的新文件
问题描述
假设我有一个字节字符串文件,如下所示:
00101000000000011000000000000011001.......
我想读取二进制文件的每 8 位并将其写入一个新文件。我如何在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
推荐阅读
- thymeleaf - thymeleaf - 如何用“测试字符串”"
- java - Java可以删除计算机的所有文件和文件夹吗?
- javascript - TypeError:无法读取 hjs-webpack 中未定义的属性“推送”
- android - 如何在本机反应中从服务器 api 获取数据
- css - 有没有办法在光标靠近按钮时使按钮可按下?
- sql - 我希望我的函数返回一个包含 # 中的数字的表
- sql - 排除选择重复
- oracle12c - 我们在我们的实例中看到以下奇怪的行为问题
- android - 如何在 RxJava flatMap 中测试函数?
- python - 如何在一系列问题中重复一个问题直到有效输入?