Reading/writing files
Matt Bergin
spam at mattbergin.co.uk
Mon Apr 14 13:53:21 EDT 2003
lost wrote:
...
> I need something like this
>
> for line in a file
> print line
> print done
for line in file('afile.txt', 'rb')
print line
print 'done'
> and for writing, I've tried doing file.write(blah) (blah is a list), but
> it wont write.
> I need to write lists into a file, but i cant. are there other methods
> for printing to a file, other than file.write?
You need to convert whatever you want to a file to a string first. Take
a look at the pickle module.
From the Python tutorial:
----------------
If you have an object x, and a file object f that's been opened for
writing, the simplest way to pickle the object takes only one line of code:
pickle.dump(x, f)
To unpickle the object again, if f is a file object which has been
opened for reading:
x = pickle.load(f)
(There are other variants of this, used when pickling many objects or
when you don't want to write the pickled data to a file; consult the
complete documentation for pickle in the Library Reference.)
----------------
Or you could do
file.write(':'.join(list))
To join the list with colons (if it is a list of strings), and to read
it back you could do
list = line.split(':')
> Also, do i need to take into account the \n at the end of a line?
line = line.rstrip() will remove the \n.
--
Matt Bergin
More information about the Python-list
mailing list