[Tutor] writing list to new file

Tony Meyer tameyer at ihug.co.nz
Mon Feb 14 04:48:19 CET 2005


> How would I save a list to a new file
> 
> for example: 
> 
> If line.startswith('XXX'):
>             save list to new file
> 
> But I get errors saying only stings can be saved this
> way. 

What do you want to do with the file afterwards?

If you want to load it back in as a list at some later point, then something
like pickle is probably what you want:

>>> l = ['1','2','3','4','5']
>>> import pickle
>>> f = open("temp.txt", "w")
>>> pickle.dump(l, f)
>>> f.close()

The file looks like this:

"""
(lp0
S'1'
p1
aS'2'
p2
aS'3'
p3
aS'4'
p4
aS'5'
p5
a.
"""

If you just want a human to be able to read the file, then you probably just
want to turn the list into a string, e.g.:

>>> l = ['1','2','3','4','5']
>>> f = open("temp.txt", "w")
>>> f.write(','.join(l))
>>> f.close()

The file looks like this:

"""
1,2,3,4,5
"""

=Tony.Meyer



More information about the Tutor mailing list