Search⌘ K

How to Read a File

Explore methods to read files in Python, including opening files with various path styles, reading entire contents or line by line, using readlines(), and handling large files in manageable chunks.

We'll cover the following...

Python has a builtin function called open that we can use to open a file for reading. For our examples in this course, we will use a text file name “test.txt” with the following contents (don’t worry, we’ve already worked with Educative to have these files uploaded to your execution directory):

This is a test file
line 2
line 3
this line intentionally left blank

Here are a couple of examples that show how to use open for reading:

Python 3.5
handle = open("test.txt")
handle = open(r"py101book/data/test.txt", "r")

The first example will open a file named test.txt in read-only mode. This is the default mode of ...