Good job! There is actually an alternative syntax when working with text files. It's the
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.
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:
- The file is automatically closed for you, so you don't have to remember about doing so yourself.
- The file handling code is indented, so it's clear where it starts and ends.