Reading and Printing a File
Let’s learn how to read a file in Python.
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.
Create a free account to view this lesson.
By signing up, you agree to Educative's Terms of Service and Privacy Policy