Reading and Printing a File
Explore how to handle plain text files in Python by reading and printing their contents. This lesson helps you understand file modes, opening and closing files, and prepares you to build a simple word counting tool based on a real Linux utility.
We'll cover the following...
Linux built-in word count utility
We will begin by building a simple utility called word counter. If you’re familiar with Linux you’ll know this as the wc utility. On Linux, we can type:
wc <filename>
This gets the number of words, lines, and characters in a file. The wc utility is quite advanced since it has been around for a long time. So, we’re going to build a baby version. This will hopefully be more interesting than printing “Hello World” to the screen.
With that in mind, let’s get started!
#!/usr/bin/python
The first line that starts with a #! is used mainly on Linux systems. It tells the shell that this is a Python file and should be run as such. It also tells Linux which interpreter to use (Python in our case).
Note: The
#!shell doesn’t harm Windows. This is because, in Python, anything that starts with#is a non-executable comment in the code.
Reading plain text files
Let’s look at the code, “File reading using Python”.
STRAY BIRDS
BY
RABINDRANATH TAGORE
STRAY birds of summer come to my
window to sing and fly away.
And yellow leaves of autumn, which
have no songs, flutter and fall there
with a sigh.
In line 3, we opened a file called birds.txt, as shown above.
It must already exist in the current directory (the directory we are running the code from). Later on in the lesson, we will cover reading from the command line, but the path is hardcoded for now. The r means the file will be opened in a read-only mode. Other common modes are w for write, a for append.
We can also read and write binary files. However, we won’t go into that at the moment. For now our files are plain text.
In lines 5-7 above, we opened the file, read its contents into a variable called data, closed it, and printed it. And now, to test our code. If we are on Linux, we can type:
./read_file.py
To run it we might have to make the file executable. So on Windows, we’ll need to do the following:
python read_file.py
And there we go! Our first Python program.