Kodeclik Blog

How to Open a Text File in Python

Python programs typically contain only the code needed to process data or content and they often read the data or content from an external file. In this blogpost, you will see how to write such programs.

Creating a data file

First, let us create a simple data file containing months and seasons, like so:

Opening, reading, and closing the data file

Let us name this file “seasons.txt”. Now we can open the file using the following Python program:
The first line opens the file for reading (hence the “r” argument). This means that we are only going to use the file for input, not for output. The function open() returns a file object, in this case “f”. All future operations with this file are referred to using this file object.
The second line reads from the file using the read() function. The results of the read() are the entire contents of the file which we print using the print() function.
Once the file is processed, we close the file using the close() function. It is always good programming practice to close your files after you are done with all necessary operations on them.

Reading files line by line

Note that the read() function reads the full content of the file in one go. This is fine if we do not require fine-grained access to individual lines or characters of the file.
If you desire to read the file line by line, you can use the readline() function.
Running the above program gives:
Note that it prints an extra line - but there is no blank line in our file. Why?
This is because when it reads the line it reads the line along with the last character (which is the carriage return). When it prints it, remember print adds its own newline. This is why you get 2 newlines.
Try doing:
We get:

Reading files using a for loop

You can also loop through each line of the file instead of reading them all in one go.
This will yield:
We can also to take each line and print them in a different order:
This gives, as expected:

Reading files using readlines()

Just like readline() reads one line of the file at a time and returns a string, readlines() reads all lines of the file and returns a list of strings:
Note that each line’s newline character is packaged as part of the string when reading that line (except the latd line which does not have a newline).

Reading a file that does not exist

Sometimes we might be reading from a file that does not exist. Let us make a spelling mistake in the name of our seasons file and see what happens.
As you can see we get a “no such file or directory” error. This is usually because Python is looking in the current directory for the file whereas the file might be residing in a different directory. You should give the full pathname whenever you attempt to read a file.
In general, it is good programming practice to trap for exceptions. We can use a “try except” block like so:
This will yield:
If the season.txt file does not exist.
In this blogpost, you have learnt how to open a file, read its contents, and close the file. It is good programming practice to specify the full pathname of the file and also trap for exceptions. Now that you have learnt how to open and read a file, proceed onto our blogpost on how to write to files in Python! Also learn how to create directories programmatically in Python.
If you liked this blogpost, you will also find useful our blogpost on determining a file's size within Python. Also learn other ways to split a text file by lines in Python.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.

Join our mailing list

Subscribe to get updates about our classes, camps, coupons, and more.

Copyright @ Kodeclik 2024. All rights reserved.