Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
The very basics of text files
with statement and exception handling
8. with statement


Good job! There is actually an alternative syntax when working with text files. It's the with statement:

with open('employees.txt', 'r') as file:
  for line in file:
    print('Employee: ' + line)

On line 1, we start by writing with and create a file object by executing open('employees.txt', 'r'). This file object is assigned to a variable named file (here, you can choose any name you want). At the end of the line, there is a colon.

Next, the with statement requires an indented block of code, just like loops and if statements do. Inside the indented block, you can use the file variable declared on line 1. It has the same functions as before. The file variable refers to the file object and allows you to access lines in the file. Note that there is no file.close() at the end – this part automatically handled for you.

The code above will work exactly as the code shown before, but it has the following advantages:

  1. The file is automatically closed for you, so you don't have to remember about doing so yourself.
  2. The file handling code is indented, so it's clear where it starts and ends.


The template code presents a solution to an earlier exercise. Modify the code so that it uses a with statement.

Stuck? Here's a hint!

Remember: you don't need to close the file anymore.