import struct
import os
# 文件头长度
# header_length = 24
def read_and_save_bx_csv(echo, csv):
"""
Read a fcd file and save it as a bx csv file.
:param fcd: 输入文件
:param csv: 输出文件
:return:
"""
# f = open(echo, 'rb')
# f.seek(0, 2)
# 第一个参数表示偏移量(正数表示向后移动,负数表示向前移动),
# 第二个参数表示位置(0--文件开头,1--当前位置,2--文件末尾)
# seek(0, 2)表示移到与末尾相差0的位置,也就是末尾的位置
# eof = f.tell() # 得到文件末尾的数值
with open(echo, 'rb') as r, open(csv, 'w') as w:
# 忽略文件头
#file.seek()方法标准格式是:file.seek(offset,whence)
# offset:开始的偏移量,也就是代表需要移动偏移的字节数
# whence:给offset参数一个定义,表示要从哪个位置开始偏移;0代表从文件开头开始算起,1代表从当前位置开始算起,2代表从文件末尾算起。whence值为空没设置时会默认为0。
# r.seek(header_length)
r.seek(0, 2)
eof = r.tell()
r.seek(0,0) #移到文件头
while True:
data = r.read(4)
test_ID = int.from_bytes(data, byteorder='little', signed=False)
data = r.read(4)
gates = int.from_bytes(data, byteorder='little')
data = r.read(4)
depth = int.from_bytes(data, byteorder='little')
data = r.read(4)
Aid = int.from_bytes(data, byteorder='little')
data = r.read(4)
amplitude = int.from_bytes(data, byteorder='little')
data = r.read(4)
threshold = int.from_bytes(data, byteorder='little')
w.write(f'{test_ID},{gates},{Aid},{depth},{Aid},{amplitude},{threshold}\n')
if r.tell() >= eof: # 将当前位置与文件尾(eof)比较
break
r.close()
if __name__ == '__main__':
# file_name = 'F:/dFile/1.echo'
file_name = 'F:/dFile/1.echo'
# bx_csv_name = 'F:/test csv/bx.csv'
bx_csv_name = 'F:/test csv/bx.csv'
read_and_save_bx_csv(file_name, bx_csv_name)
python读取二进制
最新推荐文章于 2024-01-20 14:01:29 发布