Ada*_*obb 1 python struct binaryfiles
我如何在Python中打开二进制数据文件并一次一个地读回值long
到结构中.我现在有这样的东西,但我认为这将继续覆盖idList,我想追加它,所以我最终long得到文件中所有值的元组-
file = open(filename, "rb")
try:
bytes_read = file.read(struct.calcsize("=l"))
while bytes_read:
# Read 4 bytes(long integer)
idList = struct.unpack("=l", bytes_read)
bytes_read = file.read(struct.calcsize("=l"))
finally:
file.close()
Run Code Online (Sandbox Code Playgroud)
最简单(python 2.6或更高版本):
import array
idlist = array.array('l')
with open(filename, "rb") as f:
while True:
try: idlist.fromfile(f, 2000)
except EOFError: break
idtuple = tuple(idlist)
Run Code Online (Sandbox Code Playgroud)
元组是不可变的,所以它们不能被逐步建成:所以,你必须建立一个不同(可变)序列,然后调用tuple在年底就可以了.当然,如果你实际上并不需要专门的元组,你可以保存最后一个昂贵的步骤并保留数组或列表或其他任何内容.file无论如何,避免践踏内置名称是可取的;-).
如果您必须将struct模块用于最好由array模块处理的作业(例如,因为下注),
idlist = [ ]
with open(filename, "rb") as f:
while True:
bytes_read = f.read(struct.calcsize("=l"))
if not bytes_read: break
oneid = struct.unpack("=l", bytes_read)[0]
idlist.append(oneid)
Run Code Online (Sandbox Code Playgroud)
该with声明(2.5也可与进口的形式在未来)比旧式的try /终于在清晰和简洁,更好.
| 归档时间: |
|
| 查看次数: |
7415 次 |
| 最近记录: |