Python 101Free
MODULES AND FILES

File I/O

Read from and write to files on disk.

SECTION 01

open and file modes

open(path, mode) returns a file object. The mode is a short string. r means read (the default), w means write (truncate the file or create it fresh), a means append (write at the end without overwriting). For text files, also pass encoding="utf-8"; without it Python guesses, and the guess can be wrong on Windows.

The file object is a resource. It holds an open handle and needs to be closed when you are done. The right way to handle this is to use open inside a with block. The with statement closes the file automatically when the block exits, including if an exception is raised in the middle.

Forget to close a file and you may run out of file descriptors, lose unwritten data, or hold a lock you do not need. The with form makes the issue impossible to forget.

python
with open("notes.txt", "a", encoding="utf-8") as f:
    f.write("new line\n")
# 'r' read (default), 'w' truncate, 'a' append
2 more sections

Create a free account to access all sections and animations.

Create free accountAlready have an account? Sign in