需求:将Test文件夹下所有bin文件中凡是出现128的统一替换成129。
import os
root = r'D:\TXB\Y2022\PROJ\S2106\INNER\内部研究\语音信号处理\智能语音处理\test\pattern_0513'
for file in os.listdir(root):
if file.endswith('.bin'):
src_path = os.path.join(root, file)
src_file = open(src_path, 'rb')
dst_path = os.path.join(root, file.split('.')[0] + '_dst'+'.bin')
dst_file = open(dst_path, 'wb')
for i in range(os.path.getsize(src_path)):
# 每次读1个字节,读出类型为bytes字节数组,按大端模式转换成整形,big即大端模式,MSB最高有效位在低地址
data = int.from_bytes(src_file.read(1), byteorder = 'big')
if data == 128:
data = 129
# 将整形按大端模式转换成bytes字节数组
dst_file.write(data.to_bytes(1, 'big'))
else:
dst_file.write(data.to_bytes(1, 'big'))
src_file.close()
dst_file.close()
常见的file
操作模式:
- read 打开&读取
–r
:打开指定文件,只用于reading
。文件指针在开头。python的默认模式。若无指定文件则报错
–·rb
:以二进制执行的r
; - write 打开&覆盖
–w
:打开指定文件,只用于writing
。如果文件存在,则先删除(表里所有的)已有数据,如果不存在,则创建;
–wb
:以二进制执行的w
; - append 打开&添加
–a
:打开指定文件,用于appending
。如果文件存在,指针放在结尾,如果文件不存在,则创建;
–ab
:以二进制执行的a
;