By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,763 Members | 1,563 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,763 IT Pros & Developers. It's quick & easy.

write data file

P: n/a
Question from a newbie. How do you write out a data file of floating
point numbers? file.write only takes strings.
Many thanks.
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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.


Have a look at struct http://www.python.org/doc/2.3.3/lib/module-struct.html
Yermat

Jul 18 '05 #2

P: n/a
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

Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.