Skip to content

Instantly share code, notes, and snippets.

@seanh
Created November 12, 2009 11:19
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanh/232829 to your computer and use it in GitHub Desktop.
Save seanh/232829 to your computer and use it in GitHub Desktop.
Writing text files in Python
# Write mode creates a new file or overwrites the existing content of the file.
# Write mode will _always_ destroy the existing contents of a file.
try:
# This will create a new file or **overwrite an existing file**.
f = open("file.txt", "w")
try:
f.write('blah') # Write a string to a file
f.writelines(lines) # Write a sequence of strings to a file
finally:
f.close()
except IOError:
pass
# Append mode adds to the existing content, e.g. for keeping a log file. Append
# mode will _never_ harm the existing contents of a file.
try:
# This tries to open an existing file but creates a new file if necessary.
logfile = open("log.txt", "a")
try:
logfile.write('log log log')
finally:
logfile.close()
except IOError:
pass
# There are also r (read) and r+ (read and write) modes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment