Modal Title
Data Science / Software Development

Python for Beginners: How to Read Text from a File

Reading text from a file using Python programming is possible. Discover how to do it in this Python for Beginners article.
Feb 23rd, 2022 9:00am by
Featued image for: Python for Beginners: How to Read Text from a File

We’re back with more Python goodness from a beginner’s perspective. Our goal with this series is to make the Python language easy to learn and use. So far we’ve learned about data types, the range() function, and/or operators, functions, saving input to a file, the python console,  and what makes Python special. All of these entries should add together to help you understand the basics of Python as well as some fundamental concepts of programming in general.

One of the things I hope you’ve grown to understand is just how easy Python is to learn as well as how useful it can be. With enough skill and creativity, you can make this language do quite a bit.

I want to introduce you to yet another very handy feature of Python, the ability to open external files and read them. This is a very simple concept to understand and the application of it can really help you grow as a Python programmer.

But what type of implications does reading a file with Python have? What can you use it for?

Say, for example, you create a small program that reads data from one file and saves it a sort of database of information. With such an application, you would only need to edit the source file to then add more entries to the save-to file.

But how is this done?

What You’ll Need

As with all of the articles in this series, you’ll need Python installed (which can be used on Linux, macOS, or Windows). I’ll be demonstrating on Ubuntu Linux, but all you’ll need to change is the tool you use for creating new text files.

Introducing the open() and close() Functions

The method of reading data from a file is handled with the open() and close() functions. Once you have the file open, you can apply other concepts that you’ve already learned (such as a for loop or the print() function).

We use both the open() and close() functions together because if we don’t use the close() function the file we opened will remain open, which can cause problems later on.

First, we’re going to learn how to use the open() function to read and print out the contents of a file containing Shakespear’s Sonnet 145. First, let’s create a file named sonnet.txt with the command:

nano sonnet.txt

In that file, paste the following content:

Those lips that Love’s own hand did make
Breathed forth the sound that said ‘I hate’
To me that languish’d for her sake;
But when she saw my woeful state,
Straight in her heart did mercy come,
Chiding that tongue that ever sweet
Was used in giving gentle doom,
And taught it thus anew to greet;
‘I hate’ she alter’d with an end,
That follow’d it as gentle day
Doth follow night, who like a fiend
From heaven to hell is flown away;
‘I hate’ from hate away she threw,
And saved my life, saying ‘not you.’

Save and close the file.

Now, we’re going to create a python script to read the contents of that file and then print them out in the terminal. Create the new Python script with:

nano read_in.py

First, we open the sonnet.txt file for reading with the line:

myfile = open(“sonnet.txt”)

Next, we’ll use a for loop to print out the file, one line at a time. That loop looks like this:

Our entire script looks like this:

Save and close the file. Run the Python script with the command:

python3 read_in.py

You should see each line of the sonnet printed in the output.

One thing we should also take care of is closing that file (just to be safe). We can use the close() function to close the file with the line:

myfile.close()

So, now our script looks like this:

How to Read Input and Write It to Another File

Let’s take this to the next level. What we’re going to do now is read the contents of sonnet.txt and write it to poem.txt. First, create the script with:

nano write_out.py

In the first section of the script, we’ll open the first file (sonnet.txt) for reading and open the second file (poem.txt) in append mode (because we might not want to overwrite what’s already in the file.

That line looks like this:

with open('sonnet.txt','r') as firstfile, open('poem.txt','a') as secondfile:

So we’ve defined sonnet.txt as firstfile and poem.txt as secondfile. We can now use a for loop to read in each line from firstfile and then append it to secondfile. Those lines of the script look like this:

for line in firstfile:secondfile.write(line)

Our entire script looks like this:

Save and close the file.

Run the script with the command:

python3 write_out.py

The command will complete very quickly and you should find a new file, named poem.txt, in the same directory as the script. The contents of poem.txt should match that of sonnet.txt. If you run the script again, you’ll find it appends the full sonnet at the end of the first. Keep running it and let’s keep appending the text.

If, on the other hand, you don’t want to append, you could open secondfile for writing (which will overwrite the original content in poem.txt) with the line:

with open('sonnet.txt','r') as firstfile, open('poem.txt','w') as secondfile:

We’ve changed a (for append) to w (for write). Now, no matter how many times you run the script, there will only be one copy of the sonnet in poem.txt.

And that’s how you read text from a file and write it to another file using Python. This trick will come in handy with a lot of your Python applications.

Group Created with Sketch.
THE NEW STACK UPDATE A newsletter digest of the week’s most important stories & analyses.