Chinaemerem Obidoo
Chimexis Tech Blog


Chimexis Tech Blog


Reading and Writing Text Files in Python: A Comprehensive Approach

Chinaemerem Obidoo's photo
Chinaemerem Obidoo
·Jul 9, 2022·

5 min read

Table of contents

  • File Operations

This article discusses the procedures for reading and writing to a text file in Python. No deep programming knowledge is required as the code snippets are pretty easy to grasp.

We begin by discussing "Files".


The idea of files in computing is modeled after the real-world file system. Consider an office cabinet that is used to store files. Each file may contain a specific type of information such as sales records or employee data and is kept in a specific compartment in the cabinet.

Similarly, computer files are of different types depending on the kind of information they hold, as indicated by the extension appended after the file name. We have text files (with .txt extension), PowerPoint presentation files (with .PPTX extension), and so on. The files are also stored at specific locations in the computer storage.

Moreover, this article focuses on text files. Text files contain simple text documents.

File Operations

The three main operations that can be performed on files in Python are:

1. Opening a file

In Python, you can create a new file or open an existing one using the built-in Open() function. You specify the file name and also the 'mode' as arguments.

The mode tells whether you want to read from the file, write to the file, or append new text to the file. Below is a brief description of the different mode arguments.

r: Opens a file for reading (default).

w: Opens a file for writing. Creates a new file if it does not exist or overwrites it if it exists.

a: Opens a file for appending at the end of the file without overwriting it. Creates a new file if it does not exist.

The Open() function returns a file object that is stored in a variable, which in turn is used to read or modify the file by applying various file objects.

# if the file is in the program directory, specify file name only
file = open ("words.txt", 'r')
# if the file is in a different directory, specify the full path
file = open ("C:\Projects\newlibrary\words.txt", 'r')

2. Reading from a file

To read from a file in Python, you must open the file in the read mode, r. Various methods exist that enable one to read from an open file. This depends on how you want to read the data into the file object.

read(n): Reads at most n characters at a time. Reads till the end of the file if n is negative or None.

readable(): Returns True if the file stream can be read from.

readline(): Reads and returns one line from the file.

readlines(): Reads and returns a list of lines from the file.

Given a text file "me.txt" containing the following body of wordings:

                I am a good man.
                I am intelligent.
                I am brave.

Calling the different read methods will look thus:

f = open("me.txt", 'r')
# read the first four characters
output: I am
#calling the read(n) method again returns the next n characters
# read the first line from the file
output: I am a good man.
# calling the readline() method again returns the next line of characters
# print out a list of all lines
output: ['I am a good man.', 'I am intelligent.', 'I am brave.']

3. Writing to a file

Before writing to a file, you must open it in the write mode w, or the append mode, a.

For the write mode, every preexisting data is overwritten and all previous data is erased. On the other hand, the append mode does not overwrite any preexisting data but rather adds new content to the end of the file.

The methods described next are associated with writing and appending to a file.

write(s): Writes the string s to the file and returns the number of characters written.

writelines([lines]): Writes a list of lines to the file.

writable(): Returns True if you can write to the file.

# create a new file
new_file = open("sport.txt", 'w')
# write the first line to the file
new_file.write("I love sports\n")
# write the second line to the file
new_file.write("My favorite sport is football\n")

Notice that we included the new line character \n so that each string of characters is printed on a separate line. The program creates a new file sport.txt if it does not exist already or overwrites it if it does. The program outputs:

                 I love sports
                 My favorite sport is football

Taking it a step further, we can append some text to the file above as shown next.

# open the file
prev_file = open("sport.txt", 'a')
# append a new line to the file
prev_file.append("Messi is my favorite footballer")

The content of the sport.txt file now looks like this:

                I love sports
                My favorite sport is football
                Messi is my favorite footballer

3. Closing a file

After reading, writing, and/or appending to a file, it is imperative to close the file.

You can close a file exclusively by using the close() method on the file object.

#close the file we opened above

However, a better way to close a file is by using the with statement. This ensures that the file is closed automatically when the block inside the with statement is exited. In this case, we don't have to explicitly call on the close() method as we did previously.

with open("test.txt", 'r+w') as file2:
        # perform file operations.
Share this