Better Programming

Advice for programmers.

Follow publication

Member-only story

A Cheat Sheet on Reading and Writing Files in Python

Yong Cui
Better Programming
Published in
6 min readJan 13, 2020
Photo by Álvaro Serrano on Unsplash

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.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Yong Cui
Yong Cui

Written by Yong Cui

Work at the nexus of biomedicine, data science & mobile dev. Author of Python How-to by Manning (https://www.manning.com/books/python-how-to).

Responses (1)

Write a response