Programming with Python - the beginners' course

Opening and Reading Python Files: A Guide for Beginners

All videos of the tutorial Programming with Python - the beginners' course
Denis Panjuta
By Denis Panjuta Last updated on Shown in: Python 3.5

You want to read text files in Python, for example to process notes, configurations, or measurement data further? Then it's worth first understanding how access to a file actually works. In this tutorial, you'll work with a local installation instead of an online environment. You'll create a text file, open it with Python, read its content line by line, and handle errors cleanly.

Python programming for beginners - 29 Open and read files

The video is only loaded from YouTube when you play it – data (including your IP address) is then transmitted to YouTube/Google. More in the privacy policy

Introduction

So far, you have mostly run Python online in the browser. For real projects, however, it is more practical to work locally, because then your program can access files on your computer directly. For this, I'll show you the route via the Anaconda Navigator and Jupyter Notebook. At the end, you will be able to open a file, output its content, and handle errors such as missing files.

Key Takeaways

  • With the open() function, you create a file object through which you can access the file.
  • The mode "r" stands for Read and means that the file is opened for reading only.
  • A for loop over the file object reads the file line by line.
  • The rstrip() method removes superfluous spaces and the line break at the end of each line.
  • With try and except, you prevent your program from crashing when an error occurs.
  • You should always close an opened file again, preferably via finally or, even more simply, via with.

Step 1: Start Anaconda Navigator

The first step is to open the local development environment. Search your computer for "Anaconda" and start the Anaconda Navigator. There you will see an overview of all installed tools, including Spyder and Jupyter Notebook. For this tutorial, you need Jupyter Notebook.

Opening and Reading Python Files: A Beginner's Guide

Step 2: Start Jupyter Notebook and Choose the Right Folder

In the Navigator, click "Launch" for Jupyter Notebook. A browser window opens with the Jupyter file browser, and a terminal runs in the background, which you must leave open as long as you are working. Jupyter starts automatically in the documents folder. There, you now create a new folder, for example via the "New" button and "Folder". Then rename it so that you can find it quickly later.

Opening and Reading Python Files: A Guide for Beginners
Opening and Reading Python Files: A Beginner's Guide

Step 3: Create a Text File for Practice

So that there is something to read, you need a text file. Open your new folder, right-click on an empty spot, and select "New" and then "Text Document". Name the file textdatei.txt. Then open it and enter a few lines of text, for example "Zeile 1 blabla", "Zeile 2 Jo", and "Zeile 3 mehr Inhalt". Save the file afterwards so that the content is written to the hard drive.

Opening and Reading Python Files: A Guide for Beginners

Step 4: Create a Python File in the Same Folder

Now create a new Python 3 file in the same folder. In the Jupyter browser, you do this via "New" and "Python 3". Give the notebook a meaningful name such as "Dateien lesen". Since the code is executed locally, you can access the text file directly because it is located in the same folder. So you only need to specify the file name, not the complete path.

Opening and Reading Python Files: A Guide for Beginners
Opening and Reading Python Files: A Beginner's Guide

Step 5: Open the File with open()

The actual core begins with opening the file. For this, you use the built-in function open(). It returns a file object through which you can access the content. The second parameter determines the mode. With "r", you open the file for reading, while with "w" you would open it for writing, which will be covered in the next video.

dateiobjekt = open("textdatei.txt", "r")

Step 6: Read the File Line by Line

Once the file is open, you can go through each line individually with a for loop. Python delivers one line after another until the file has been read completely. Inside the loop, you output each line with print(). Since each line contains a line break at the end, you remove it with rstrip(). This method belongs to every line as a text and cleans up the content before you use it further.

for zeile in dateiobjekt:
    print(zeile.rstrip())
Opening and Reading Python Files: A Guide for Beginners

Step 7: Closing the file object again

When you have finished reading, you should close the file again. This frees up resources and prevents problems, for example when the same file needs to be edited somewhere else. To do this, you call the close() method.

dateiobjekt.close()

If you now run the code, you will see the three lines from your text file in the output. If you change the content of the file and run the code again, the new lines will appear as well.

Opening and Reading Python Files: A Beginner's Guide

Step 8: Catching errors with try and except

What happens if you make a typo in a file name? Change the name in the code to a file that does not exist and run the program. Python aborts with an error. To prevent this, you put the code in a try block. In the except block, you catch the error of type IOError and output an understandable message.

try:
    dateiobjekt = open("textdatei.txt", "r")
    for zeile in dateiobjekt:
        print(zeile.rstrip())
    dateiobjekt.close()
except IOError:
    print("Fehler aufgetreten")
Opening and Reading Python Files: A Beginner's Guide
Opening and Reading Python Files: A Guide for Beginners
Opening and Reading Python Files: A Guide for Beginners

Step 9: Closing the file reliably

The video suggests handling the closing of the file via else. One note from a technical perspective is important here: the else block is only executed if no error occurs. If one does occur, the file stays open. finally is more reliable, because this block always runs, regardless of whether an error occurred or not.

try:
    dateiobjekt = open("textdatei.txt", "r")
    for zeile in dateiobjekt:
        print(zeile.rstrip())
except IOError:
    print("Fehler aufgetreten")
finally:
    dateiobjekt.close()

The more elegant variant is the with statement. It closes the file automatically as soon as the indented block ends:

try:
    with open("textdatei.txt", "r") as dateiobjekt:
        for zeile in dateiobjekt:
            print(zeile.rstrip())
except IOError:
    print("Fehler aufgetreten")
Opening and Reading Python Files: A Guide for Beginners

Outlook: What you can use file reading for

With these basics, you can read out any text files completely, break them down into individual parts in your program, and use the information in a targeted way. Later, you will learn with regular expressions how to search and analyze texts even more precisely.

Summary ??? Opening and reading Python files: explained step by step

You have learned how to work locally with Anaconda and Jupyter Notebook, create a text file, and open it in read mode with open(). You know the for loop, with which you read out lines individually, and you know how to remove unwanted line breaks with rstrip(). In addition, you can catch errors with try and except and close the file reliably with finally or with. The next step is about how to write content to a file.

FAQ

What do I need to follow this tutorial?You need a local installation of Anaconda, which includes Jupyter Notebook. An online environment does not work for this, because it does not allow direct access to your files.

Why does the Jupyter terminal have to stay open?The terminal runs the Jupyter server. If it is closed, the notebook can no longer run.

What does the mode "r" mean in open()?The "r" stands for Read. The file is opened for reading only, so you cannot change any content.

Do I have to specify the full path to the file?No, if the Python file is located in the same folder as the text file, the file name is sufficient.

What exactly does rstrip() do?The method removes spaces and the line break at the end of a line so that the output looks clean.

Why should I use finally or with instead of else?An else block only runs if no error occurs. If an error occurs, the file would remain open. With finally or with, the file is closed in every case.

Denis Panjuta
Trainer About Denis Panjuta Hi, I'm Denis Panjuta and I have a bachelor's degree in industrial engineering from the HTWG Konstanz, where I also discovered my passion for programming. Currently, over 16,000 students are already learning from my courses. All courses by Denis Panjuta