如何有效地将二进制数据打包到Python中的文件? [英] How can I efficiently pack binary data into a file in Python?

查看:203
本文介绍了如何有效地将二进制数据打包到Python中的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用Python将二进制数据写入一个文件,而不是先通过临时缓冲区发送。如何在一个文件上直接使用 struct 模块?

解决方案

以下是我如何能够将二进制数据直接打包到Python 3下的文件中。唯一的缺点是您需要在写入数据之前猜测文件的最大大小。 (如果猜测值太大,可以额外调用 truncate )。

正在这里。该文件正在被内存映射,并且正在使用 struct 将数据打包到内存映射的 memoryview 中。通过使用 memoryview ,可以使用Python缓冲区接口直接写入文件。 struct pack_into 函数可以写入任何支持缓冲区接口的东西。通过在套接字上使用 memoryview 将二进制数据直接写入套接字,也可以使用这种技术。

 










$ b $ open('test.bin','wb')as f:
f.truncate(100 )

with open('test.bin','r + b')as f:
m = mmap.mmap(f.fileno(),0)
mv = (25):
struct.pack_into('> l',mv,ind * 4,ind)

另外请注意,调用 pack_into 的次数可能会更少,然后在循环中调用它这里仅用于说明目的。


I would like to write binary data to a file in Python without sending it through temporary buffers first. How can I use the struct module directly on a file?

解决方案

Here is how I was able to pack binary data directly into a file under Python 3. The only drawback is that you need to guess a maximum size for the file before writing the data. (An additional call to truncate can be made at the end if the guess is too big.)

Two things are going on here. The file is being memory mapped, and struct is being used to pack data into a memoryview of that memory map. By using a memoryview, it is possible to use the Python buffer interface to write directly to the file. struct's pack_into function can write into anything that supports the buffer interface. This technique can also be used by using a memoryview on a socket to write binary data directly to a socket.

import struct
import mmap

with open('test.bin', 'wb') as f:
    f.truncate(100)

with open('test.bin', 'r+b') as f:
    m = mmap.mmap(f.fileno(), 0)
    mv = memoryview(m)
    for ind in range(25):
        struct.pack_into('>l', mv, ind * 4, ind)

Also, note that it's probably better to make fewer calls to pack_into, and calling it in a loop here is just for illustrative purposes.

这篇关于如何有效地将二进制数据打包到Python中的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆