Member-only story
A Cheat Sheet on Reading and Writing Files in Python
Quick reference on how to read and write files

It’s a common task in Python programming that we need to read and write files.
This short tutorial isn’t intended to cover everything in file reading and writing in Python. Instead, I just wanted to share with you some cheat sheets that I created for reading and writing files in my daily Python programming.
Just a few housekeeping reminders to note before we move forward.
- The code presented here is written in Python 3.7.3, and doesn’t always apply to earlier versions of Python.
- We’ll focus on built-in methods that come as part of the standard package so that we don’t need to deal with installing third-party packages that are not necessarily straightforward for beginners.
- You can choose whatever Python IDE you prefer. For me, I use Visual Studio Code and Mac’s Terminal to run my code as applicable.
TL;DR
Here are the two quick cheat sheets as the takeaways for this article. The first sheet lists the key methods/functionalities involved in reading and writing files that are discussed in this article.
The second sheet lists the common open modes that are used when opening a file for proper reading/writing operations.
Open a File
open()
The first step in dealing with a file in Python is to open the file. To do that, you can just use the open()
method, which will create a file object. Specifically, this method has a set of parameters for reading a file, but the two most used arguments are the filename and the mode.