how to write a line in a text file

Dan Sommers me at privacy.net
Mon Jul 25 16:49:46 EDT 2005


On 25 Jul 2005 12:57:55 -0700,
"wittempj at hotmail.com" <martin.witte at gmail.com> wrote:

> A recipe is
> * open your file for reading: f = open('filename.txt', 'r')
> * read all lines in a list: content = f.readlines()
> * close the file: f.close()
> * set the third element in the list to something else: content[2] =
> 'Blahdiblah'

Better make that ''Blahdiblah\n' (note the trailing newline) because:
    - readlines leaves the newlines at the ends of the lines
    - writelines assumes that each line (still) contains a newline

> * re-open the file for writing: f = open('filename.txt', 'w')
> * write the list to the file: f.writelines(content)
> * close the file: f.close()

HTH,
Dan

-- 
Dan Sommers
<http://www.tombstonezero.net/dan/>



More information about the Python-list mailing list