Hi Everyone,
I have a list of numbers I'm trying to write to a file, which I want to be a binary file.
Here's my code:

nums = [0x1234, 0x5678, 0xabcd, 63, 44]

with open('filename', 'wb') as bin_file:
    for number in nums:
        bin_file.write(number)

The problem is that I keep getting an empty file, as if nothing is actually written to it.
Can someone please tell what am I missing here?

Thanks a lot :-)

Recommended Answers

You must write the information in string or actually bytes way, if you want to write binary format, you need to produce those bytes by using the struct module

import …
Jump to Post

All 2 Replies

You must write the information in string or actually bytes way, if you want to write binary format, you need to produce those bytes by using the struct module

import struct

nums = [0x1234, 0x5678, 0xabcd, 63, 44]

with open('filename', 'wb') as bin_file:
    bin_file.write(''.join(struct.pack('H', number) for number in nums))

Thanks PyTony,
let me see if I understoond you correctly.
You're saying I should either:

  1. Convert each item to a string, etc. 0xabcd to "0xabcd" and then write it.
    (won't that just write text and not the number itself?)

  2. Convert to bytes type using struct, and then use the file.write() method

Am I missing something here? I'd appreciate it if you could elborate.
Thanks again.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.