Skip to content

Instantly share code, notes, and snippets.

@seanh
Created August 10, 2009 14:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seanh/165218 to your computer and use it in GitHub Desktop.
Save seanh/165218 to your computer and use it in GitHub Desktop.
Read a file in Python
# The built-in function `open` opens a file and returns a file object.
# Read mode opens a file for reading only.
try:
f = open("file.txt", "r")
try:
# Read the entire contents of a file at once.
string = f.read()
# OR iterate over the file line-by-line:
for line in f:
# Do something with line.
# OR read one line at a time.
line = f.readline()
# OR read all the lines into a list.
lines = f.readlines()
finally:
f.close()
except IOError:
#FIXME: Do something!
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment