Reputation: 143
I have a very long list of large numbers in Python in the form
[429996711.2753906, 106845465.30664062, 47285925.673828125, 373352395.4082031, 934463030.1191406, 53994183.962890625, 455503649.6542969, 741004174.1660156, 725379998.9648438, 485329924.8046875, 16476769.255859375,...]
for example. I need to convert each number from decimal to binary, and then save these binary numbers into a raw binary file without CRLF line-endings. Would anyone be able to say how to do this? I haven't been able to find a usable answer anywhere. Thanks!
Upvotes: 0
Views: 988
Reputation: 14023
This snippet creates a file data.bin
with 88 bytes (11 doubles of 8 bytes each):
import struct
data = [429996711.2753906, 106845465.30664062,
47285925.673828125, 373352395.4082031,
934463030.1191406, 53994183.962890625,
455503649.6542969, 741004174.1660156,
725379998.9648438, 485329924.8046875,
16476769.255859375]
packed = map(lambda i: struct.pack("@d", i), data)
with open("data.bin", "wb") as fh:
for i in packed:
fh.write(i)
Upvotes: 1
Reputation: 1368
Convert your decimals to a bytearray or similar - see this SO thread on converting floats to bytearray
Write the bytearray to a file in binary mode - use the "wb" mode in an open()
function to mark the file as binary, as discussed in this SO thread on how to write a bytearray of ints to a binary file.
# make file
newFile = open("filename.txt", "wb")
# write to file
newFile.write(myBytearray)
Upvotes: 1