write data file

Peter Otten __peter__ at web.de
Mon Apr 5 03:22:52 EDT 2004


SunX wrote:

> Question from a newbie.  How do you write out a data file of floating
> point numbers? file.write only takes strings.
> Many thanks.

The easiest way is to write them in a text file, one float per line.
You can use repr() or str() to convert them to a string:

>>> somefloats = [1.2, 3.4, 5.7]
>>> f = file("tmp.txt", "w")
>>> for n in somefloats:
...     f.write(repr(n)) 
...     f.write("\n")
...

Here's how to read them back into Python:

>>> f = file("tmp.txt")
>>> readfloats = []
>>> for line in f:
...     readfloats.append(float(line))
...
>>> readfloats
[1.2, 3.3999999999999999, 5.7000000000000002]

The trailing digits are nothing to worry about (see the Python FAQ), for a
nicer appearance do

>>> str(readfloats[1])
'3.4'
>>> print readfloats[1] # uses str() for string conversion
3.4

When you are not interested in a human-readable file and have more complex
data to store, have a look at the pickle module.

Peter




More information about the Python-list mailing list