Reading and Writing Text Files with Python3

Saurabh Lambe
5 min readJun 3, 2020

Hello and welcome! I’m Saurabh Lambe, an open-source enthusiast and a Linux super nerd who loves to code in Python. I’ve always wanted to publish my own programming blog on the web for two reasons: to enhance my documenting skills, and get priceless feedback for my work. Kicking off this initiative with the first (of hopefully a series of tutorials in Python3) blog to help budding programmers and Pythonistas.

We will start off easy and take baby steps towards writing into a text file.

Reading from a file

I’ve already created a text file containing the poem Jack and Jill, you can go ahead and be creative with whatever text you wish.

$ cat poem.txt
--
Jack and Jill
Went up the hill
To fetch a pail of water,
Jack fell down
And broke his crown
And Jill came tumbling after.

So that it would be convenient, we shall save the text file and the Python source code in the same directory.

The first step in reading any text file from a Python program is to save the location of the said file in a variable. On my Linux computer, I have saved my text file at this location: /home/saurabh/Documents/python/poem.txt

Let us assign this “path” to a variable. Don’t forget to enclose the mentioned path by single or double-quotes.

file_path = '/home/saurabh/Documents/python/poem.txt'

Python3 provides a built-in function open() that allows us to open a file and perform operations on it. Now, the open() function accepts multiple arguments.

open (file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

This syntax was copied from Python3 official documentation.

The code() function takes the path of the file as its first argument. The mode option in the syntax above is the most important parameter. In this program, we shall use only the file and mode parameters. Some of the common modes that can be used are as follows:

In order to open the poem.txt file for reading, we will use the 'r' mode. To be able to print the output from the text file, we shall the open() function to poem_file variable.

poem_file = open(path, 'r')

Since our file has now been opened and assigned to the variable poem_file, we can now use it to read the file. The read() function outputs the entire content of the file as a single string.

Note: Once a file has been read using read() function, it cannot be read once again. For example, if you were to first run poem_file.read(), followed by another attempt at running the same poem_file.read() code, the second operation would return an empty string.

Here’s the complete code we’ve studied so far for reading from poem.txt:

$ cat read_poem.py
--
file_path = '/home/saurabh/Documents/python/poem.txt
poem_file = open(path, 'r')
print (poem_file.read())

Creating and writing into a file

Creating and writing into a file has the same more: 'w'. But beware, if a file with similar filename exists, this mode will erase the existing text and enter the new text.

First of all, we’ll assign a string of words to a variable. In this example, let’s assign one of Linus Torvalds’ famous quotes to the variable quote. We’ll input this line in our new text file called quotes.txt.

quote = 'The Linux philosophy is "Laugh in the face of danger". Oops. Wrong one. "Do it yourself". Yes, that\'s it.'

Just like in the previous example, we will now assign the absolute path of the file (quotes.txt in this case) we intend to create to the variable new_path.

new_path = '/home/saurabh/Documents/python/quotes.txt'

Now that the new file path is stored into a variable, we move on with opening the file in ‘write’ mode.

Note: If quotes.txt already existed before opening the file, its old contents would’ve been destroyed. You need to be careful while using the 'w' mode. If you wish to preserve existing text in the file, you should prefer using the 'a' which indicates append mode. It would append new text at the end of the file.

new_file = open(new_path, 'w')

The write operation takes a single parameter, most probably a string, and writes it to the file. If you want to start a new line in the file, you must explicitly provide the newline character.

$ cat create_write.py
--
quote = 'The Linux philosophy is "Laugh in the face of danger". Oops. Wrong one. "Do it yourself". Yes, that\'s it.'
new_path = '/home/saurabh/Documents/python/quotes.txt'
new_file = open(new_path, 'w')
new_file.write(quote)

This will create a new file called quotes.txt and it will contain the quote we had assigned to the variable in the above code. You may verify if the text file is present in the same folder where the source code exists.

Closing a file

After a file is opened in Python code, other applications on the computer automatically lose access to the file. Closing a file ensures two things:

  1. It terminates the connection between the file on the disk and the file variable from our code.
  2. It ensures other programs are able to access the file and the data maintains integrity.

The in-built close() function in Python allows us to close a file in a proper way.

$ cat create_write.py
--
quote = 'The Linux philosophy is "Laugh in the face of danger". Oops. Wrong one. "Do it yourself". Yes, that\'s it.'
new_path = '/home/saurabh/Documents/python/quotes.txt'
new_file = open(new_path, 'w')
new_file.write(quote)

new_file.close()

Remember, it is absolutely essential that you close a file after you have finished manipulating a file. Forgetting to do so might result in other programs failing to access the said file.

To wrap up, today we learned how to open a file to read, and write, and close it after we are done with editing it. Feedback regarding grammar and code, along with suggestions to improve my writing is always welcome. Thanks for reading, cheers!

--

--

Saurabh Lambe

Open minded thinker, a rebel, a football fan and a guy who loves heavy metal.