1

How can I write double precision files binary files using Python? I am doing the following presently but it is giving me single precision files:

#!/usr/bin/env python

import struct

data =[2.3715231753176,9.342983274982732]

output_file = "test.dat"
out_file = open(output_file,"wb")
s = struct.pack('f'*len(data), *data)
out_file.write(s)
out_file.close()

2 Answers 2

7

Use d to write double precision floats:

s = struct.pack('d'*len(data), *data)

f is single precision only. See the Format characters section of the struct module documentation:

For the 'f' and 'd' conversion codes, the packed representation uses the IEEE 754 binary32 (for 'f') or binary64 (for 'd') format, regardless of the floating-point format used by the platform.

Sign up to request clarification or add additional context in comments.

2 Comments

This works great. However what I was looking for was a fast way to write out binary data and read it back in to another python script at a later point in time. Using numpy.save() and numpy.load() makes this very easy. numpy.org/doc/stable/reference/generated/numpy.save.html
@poleguy: it may make it easy but that's one specific format and a hefty library dependency. Note that the question here specifically asked about using struct.pack(), and the issue was not binary data writing in general, but writing floating point values.
3

You're using the format string wrongly. To use double precision, use 'd' instead of 'f'. See the documentation for a list of format characters.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.