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

ModeDescription
'r'Open for reading (default)
error if file doesn't exist
'rb'Open for reading on binary mode
error if file doesn't exist
'w+'Open for reading and writing
truncates file if it exists
create file if it doesn't exist
'w+b'Open for reading and writing on binary mode.
truncates file if it exists
create file if it doesn't exist
'a'Open for appending,
create file if it doesn't exist
'a+'Open for reading and appending,
create file if it doesn't exist

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