How to write integers to a file?

Alex Martelli aleaxit at yahoo.com
Fri Feb 9 08:26:31 EST 2001


"Steven Sartorius" <ssartor at bellatlantic.net> wrote in message
news:wXRg6.3723$bu4.792238 at typhoon2.ba-dsg.net...
> I'm trying to write a series of whitespace delimited integers to a file.
> The 'write' method only accepts strings and using arrays produces binary
> data when I open the file with less.  What I want is somehting like
> printf for python.  Is there any easy way to do this?  (there must
> be...this is python!)

There are several.  Suppose you have a list (or other sequence) L of
integers and want to write them to a file object F, as readable digits,
one integer per line.  A few "easy ways" to obtain this are:

for i in L:
    F.write(str(i)+'\n')

for i in L:
    F.write("%s\n" % i)

for i in L:
    print >>F, i

F.writelines([str(i)+'\n' for i in L])

F.writelines(["%s\n" % i for i in L])

def myformat(i):
    return "%s\n" % i

F.writelines([myformat(i) for i in L])

F.writelines(map(myformat, L))


Alex






More information about the Python-list mailing list