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?
I would like to write binary data to a file in Python without sending
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
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
truncatecan be made at the end if the guess is too big.)Two things are going on here. The file is being memory mapped, and
structis being used to pack data into amemoryviewof that memory map. By using amemoryview, it is possible to use the Python buffer interface to write directly to the file.struct‘spack_intofunction can write into anything that supports the buffer interface. This technique can also be used by using amemoryviewon a socket to write binary data directly to a socket.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.