write data file

S

SunX

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

Peter Otten

SunX said:
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))
....[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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,181
Messages
2,570,970
Members
47,536
Latest member
VeldaYoung

Latest Threads

Top