Open and read/write 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()

print(content)
'I want to die as the day declines,
at high sea and facing the sky,
while agony seems like a dream
and my soul like a bird that can fly.

To hear not, at this last moment,
once alone with sky and sea,
any more voices nor weeping prayers
than the majestic beating of the waves.'

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,',
 'at high sea and facing the sky,',
 'while agony seems like a dream',
 'and my soul like a bird that can fly.',
 '',
 'To hear not, at this last moment,',
 'once alone with sky and sea,',
 'any more voices nor weeping prayers',
 'than the majestic beating of the waves.']

Write files

Just use open() with the right mode (see below). Most of the time 'w' will do.

with open('data/my_new_poem.txt', 'w') as f:
    f.write("""
    Demain, dès l'aube, à l'heure où blanchit la campagne,
    Je partirai. Vois-tu, je sais que tu m'attends.
    J'irai par la forêt, j'irai par la montagne.
    Je ne puis demeurer loin de toi plus longtemps.
    """)

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.