Depends on what you want to do. To append you can open it with "a":
Code:
with open("foo.txt", "a") as f:
f.write("new line\n")
If you want to preprend something you have to read from the file first:
Code:
with open("foo.txt", "r+") as f:
old = f.read() # read everything in the file
f.seek(0) # rewind
f.write("new line\n" + old) # write the new line before
To use the `with` statement in Python 2.5 you need to add "from __future__ import with_statement". Other than that, opening files with the `with` statement is definitely more readable and less error-prone than manual closing.
Bookmarks