如何读取、修改头文件并将.7文件与其其余数据一起保存?

2024-06-24 12:12:08 发布

您现在位置:Python中文网/ 问答频道 /正文

.7文件包含来自GE扫描仪的MRS数据。我想读取它的头,改变它的一些字段值,如扫描日期等,并保存一个新的.7文件修改头和其余的数据应该是相同的。你知道吗

代码:

from ctypes import *
import ge_util as utilge

class PfileHeaderLittle(LittleEndianStructure):
    """
    Contains the ctypes Structure for a GE P-file rdb header.
    Dynamically allocate the ctypes _fields_ list later depending on revision
    """
    _pack_   = 1
    _fields_ = utilge.get_pfile_hdr_fields(20.0)

hdr = PfileHeaderLittle()

fname = r"P16896.7"
filelike = open(fname, 'rb')
filelike.seek(0)
filelike.readinto(hdr)

print("hdr: ", hdr)
print("hdr: ", type(hdr.rhe_patname))
print("hdr: ", hdr.rhe_patname)
hdr.rhe_patname = b"CHANGE_IT"
print("hdr: ", hdr.rhe_patname)

with open("my_file.7", 'wb') as file:
    file.write(hdr)

输出:

hdr:  <__main__.PfileHeaderLittle object at 0x0000025F75D09F48>
hdr:  <class 'bytes'>
hdr:  b'MRS TEST1'
hdr:  b'CHANGE_IT'

这段代码读取标题,修改一个字段并将其保存回去。但是,其余的数据不会被保存。我再次读取了保存的文件并确认了头文件已修改,但新文件中没有剩余的数据。如何保存修改后的头文件,并与其他数据一起保存新文件?

这里是ge_utilhttps://scion.duhs.duke.edu/vespa/project/export/3828/trunk/common/ge_util.py
P16896.7文件:https://drive.google.com/open?id=1zqQbOUwlIa1_rv9OAVA0sQfEEaOFsne0


Tags: 文件数据fieldshdrutilopenctypesfile
1条回答
网友
1楼 · 发布于 2024-06-24 12:12:08

修改hdr后,按len(bytes(hdr))查找其字节长度。使用seek到达该位置和read()文件的其余部分。现在,将其与新头连接起来,并保存一个新文件:

filelike.seek(len(bytes(hdr)))
b = filelike.read()

c = bytes(hdr)+b

file = open('New_File.7', 'wb')
file.write(c)
file.close()

相关问题 更多 >