How to Open Files Effectively in Python 3

A beginner’s guide to the open() function and context blocks.

Oren Cohen
CodeX
Published in
3 min readMay 18, 2021

--

Photo by Chris Ried on Unsplash

Python 3 provides a built-in function that you can use to open files:

open("readme.txt")

This way is the easy, naive one to read a text file:

my_file_handler = open("readme.txt", "r")
my_file = my_file_handler.read()
my_file_handler.close()

I’ll give you a better way to do so, but for now, let’s go over some definitions.

File Handler Parameters

You give open() the path to a file, and based on how you want to process the file, choose the mode to operate. There are a few basic options here:

  • “r” — open a text file to read-only. Use this parameter for reading text files.
  • “rb” — open a binary file to read-only. This parameter is best for reading binary files you saved to the disk or other files you need to process, and you know their binary structures (serialized objects, lists, classes, etc.)
  • “w” — open a text file to write only. This parameter is best when you want to save lines of text to a file — like logs. When using this mode, you can select a non-existent path, and if Python can write to that location, it will create the file…

--

--