Reading/writing files
Asun Friere
afriere at yahoo.co.uk
Tue Apr 15 02:03:41 EDT 2003
Brian Quinlan <brian at sweetapp.com>
> How do you want the list represented in the file? One element per line?
Maybe he wants them represented as lists (ie as a string representation of the list)
You _could_ do this:
#!/usr/bin/python
#silly_list_writer.py
#create some sample listage
a=5;b=3;c=1
x=[a,b,c];y=[a,b];z=[c,b]
#open a file to write these to, convert em to strings and write em.
outfile = file('lists.txt', 'w') #note the write flag
for lizt in x, y, z :
outfile.write(str(lizt) + '\n')
outfile.close()
#now read them back into 'collection'
collection = []
infile = file('lists.txt', 'r') #read flag is optional
for line in infile :
collection.append(eval(line))
infile.close()
#ok lets test that the collection really is [x, y, z]
print collection == [x,y,z] and "It worked!" or "Darn!"
#Note: don't use this last idiom, unless you understand why
#(and when) it is unsafe. Gee, I really wish 308 would fly
#so people would stop writing stuff like this! :p
As I said you _could_ do this, but you should probably try this code instead:
import pickle; help(pickle)
More information about the Python-list
mailing list