1

I'm trying to output some data from a python script to a binary file.

If I have a list of floats I've been using this

out_file = open("filename", "wb")
float_array.array("f", [])
float_array.fromlist(mylist)
float_array.tofile(out_file)
out_file.close()

This seems to work fine, at least it's resulting in a file with the correct number of bytes.

How can I do the same thing but using a list of complex numbers?

Thanks

2
  • For complex numbers there is no standard binary representation (at least that I am aware of), so you will first have to decide how you want them represented. Commented May 17, 2011 at 9:52
  • I would be happy to have them as a list of doubles or floats. It doesn't really matter as long as I can read them back. Commented May 17, 2011 at 10:26

2 Answers 2

2

Don't invent your own serialization methods when Python offers so many good ones out of the box! I suggest you use pickle - it works with complex numbers as well (*):

>>> import pickle
>>> s = pickle.dumps([1+2j, 5-1j])
>>> pickle.loads(s)
[(1+2j), (5-1j)]

I'm using dumps for demonstration here, you can also use dump which writes to a binary file.


(*) From the doc of pickle:

The following types can be pickled:

  • None, True, and False
  • integers, long integers, floating point numbers, complex numbers
  • normal and Unicode strings
  • tuples, lists, sets, and dictionaries containing only picklable objects
  • functions defined at the top level of a module
  • built-in functions defined at the top level of a module
  • classes that are defined at the top level of a module
  • instances of such classes whose __dict__ or __setstate__() is picklable (see section The pickle * protocol for details)
Sign up to request clarification or add additional context in comments.

3 Comments

Remember dumping when writing a pickle file to use binary mode ;)
Thanks, I'm not sure if this is going to work. It seems to be writing a lot more data than I expect. I need to be able to read this data from C code so I need raw binary data.
@rvabdn: Python's cPickle is implemented in C, you could probably get it to work from C code. Maybe this is all too complex for your needs, but I'm just leaving it as a suggestion
1

You could create a flattened list of floats out of your complex array like

flattend = [f for sublist in ((c.real, c.imag) for c in complex_list) for f in sublist]

and write this one to the file.

1 Comment

This is the route I went in the end.

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.