Open and files in Python

Read files

Using read() will store all the file content into a single string:

# Read all file into a string
with open('data/poem.txt') as f:
    content = f.read()

content
'I want to die as the day declines, \nat high sea and facing the sky, \nwhile agony seems like a dream \nand my soul like a bird that can fly. \n\nTo hear not, at this last moment, \nonce alone with sky and sea, \nany more voices nor weeping prayers \nthan the majestic beating of the waves. \n'

To store each file line as an element of a list, use readlines():

# Read line by line into a list
with open('data/poem.txt') as f:
    content_l = f.readlines()

content_l
['I want to die as the day declines, \n',
 'at high sea and facing the sky, \n',
 'while agony seems like a dream \n',
 'and my soul like a bird that can fly. \n',
 '\n',
 'To hear not, at this last moment, \n',
 'once alone with sky and sea, \n',
 'any more voices nor weeping prayers \n',
 'than the majestic beating of the waves. \n']

Files open modes

Here are the most common open modes (refer to full documentation). They can be combined, e.g. rb+ will open a file for both reading and writing, in binary format.

Mode Explanation
r Opens a file for reading only. The file pointer is placed at the beginning of the file. This is the default mode.
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.
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.
+ Opens a file for updating (reading and writing).
b Opens a file in binary mode.
x Open for exclusive creation, failing if the file already exists.