Python Open File: Reference and Examples

Python Open File: Reference and Examples

Last updated:
Table of Contents

Using python Version 3.x on Linux (ubuntu)

Open file modes

Mode Description Cursor starts at
'r'Open for reading
error if file doesn't exist
0 (start of file)
'rb'Open for reading on binary mode
error if file doesn't exist
0 (start of file)
'w+'Open for reading and writing
truncates file if it exists
create file if it doesn't exist
0 (start of file)
'w+b'Open for reading and writing on binary mode.
truncates file if it exists
create file if it doesn't exist
0 (start of file)
'a'Open for appending,
create file if it doesn't exist
0 (start of file) if the file doesn't exist and was just created, end of file if it does exist.
'a+'Open for reading and appending,
create file if it doesn't exist
0 (start of file) if the file doesn't exist and was just created, end of file if it does exist.

Move cursor to start of file

0 refers to the first byte

f.seek(0)

with open(filepath, "a+") as f:  
    f.seek(0)

Open file for append

# file will be created if it doesn't exist
with open("my-file.txt","a") as f:
    f.write("this will be added at the end of the file\n")

Dialogue & Discussion