Created
August 10, 2009 14:11
-
-
Save seanh/165218 to your computer and use it in GitHub Desktop.
Read a file in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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