How To Read and Write Files in Python

A beginner’s guide to file I/O

Jonathan Hsu
Code 85

--

Photo by Kolar.io on Unsplash

File I/O (input/output) is a core skill that everybody should learn. Whether you want to create simple personal scripts or plan on diving into data science, file I/O is a common need that is fortunately easy to implement.

In this article, we’ll introduce how to both read and write files in Python. After introducing the skills, we’ll discuss some design considerations to avoid common pitfalls.

Opening Files

Before we begin reading or writing, the first step is actually opening the file.

To do this, we’ll use the open() function which creates a file pointer. Our pointer will be stored in a variable. We need to specify in which way we are planning on interacting with the file. There are four modes to interact with a file: read (r), write (w), append (a), and create (x).

We’re going to focus on read, write, and append for the remainder of this guide. So let’s take a look at some sample code:

filename = "app.log"with open(filename, "r") as f:
print(f)
# <_io.TextIOWrapper name='app.log' mode='r' encoding='cp1252'>

First, we assign our file’s name to a variable called filename. Then we use the with keyword in tandem…

--

--