Python Open File: Reference and Examples

Last updated:
Table of Contents

WIP Alert This is a work in progress. Current information is correct but more content may be added in the future.

Using python Version 3.6 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
'wb'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 appending

# 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")

References

Dialogue & Discussion