Skip to content

Instantly share code, notes, and snippets.

@dsaiztc
Last active September 2, 2015 12:25
Show Gist options
  • Save dsaiztc/d703cf499640367d3876 to your computer and use it in GitHub Desktop.
Save dsaiztc/d703cf499640367d3876 to your computer and use it in GitHub Desktop.
# Count the number of lines within a file
num_lines = sum(1 for line in open('myfile.txt'))
filename = 'my_file.txt'
# Read file (default mode='r')
with open(filename) as f:
file_s = f.read() # Read the whole document
with open(filename) as f:
for line in f:
line_s = line
with open(filename) as f:
f.readline() # Read first line
f.readline() # Read second line
# Skip the first N lines
N = 14
with open(filename) as f:
for _ in xrange(N):
next(f) # Or f.readline()
for line in f:
line_s = line
with open(filename, 'r') as f:
for line in f:
pass
# Equivalent but without open(...) -> Have to call close()
f = open(filename)
try:
do_stuff()
finally:
f.close()
# If we want to handle the error in accessing the file
try:
with open(filename) as f:
do_stuff_that_fails()
except (IOError, OSError) as e:
do_other_stuff_when_it_we_have_file_IO_problems()
try:
f = open(filename)
try:
do_stuff_that_fails()
except EXPECTED_EXCEPTION_TYPES as e:
do_stuff_when_it_doesnt_work()
finally:
f.close()
except (IOError, OSError) as e:
do_other_stuff_when_it_we_have_file_IO_problems()
# Write to file
with open(filename, 'w') as f:
f.write('something to write')
f.write('\n')

Here is a list of the different modes of opening a file:

r

Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.

rb

Opens a file for reading only in binary format. The file pointer is placed at the beginning of the file. This is the default mode.

r+

Opens a file for both reading and writing. The file pointer will be at the beginning of the file.

rb+

Opens a file for both reading and writing in binary format. The file pointer will be at the beginning of the file.

w

Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

wb

Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.

w+

Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

wb+

Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

a

Opens a file for appending. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

ab

Opens a file for appending in binary format. The file pointer is at the end of the file if the file exists. That is, the file is in the append mode. If the file does not exist, it creates a new file for writing.

a+

Opens a file for both appending and reading. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

ab+

Opens a file for both appending and reading in binary format. The file pointer is at the end of the file if the file exists. The file opens in the append mode. If the file does not exist, it creates a new file for reading and writing.

About the b mode

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

When opening a binary file, you should append 'b' to the mode value to open the file in binary mode, which will improve portability. (Appending 'b' is useful even on systems that don’t treat binary and text files differently, where it serves as documentation.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment