Question about reading files (Beginner)

Hello, I’m a beginner with using Python. :blush:

I have te following working code:

employee_file=open("employees.txt", "r") 

for employee in employee_file.readlines(): 


My question is why writing employee_file() in the for loop results in an error:

employee_file=open("employees.txt", "r") 

for employee in employee_file(): 


I thought maybe I could at least print every element in the file that way?

Also another small question: why is it useful to close the file? Like what do I lose from leaving it open?

employee_file is a reference to an open file. Those objects are not callable. You can just iterate over the file:

for employee in employee_file:

Closing the file is necessary when you open a number of files sequentially because there are limits on the amount of open files in the operating system. When you are writing to files closing will also flush any buffered data to the file. That said, if you don’t close the file Python will close the file for you when the file object (employee_file) is no longer referenced, or when the scripts exits.

1 Like

As an addendum to this, in Python the usual idiom is this:

with open(filename,...) as f:
    ... do things with f, the open file ...

which closes the file for you on exiting the “with”. In particular, it
will reliably close the file even you write comething like this:

def scan_some_file(filename):
    with open(filename,.....) as f:
        for line in f:
            if "quit now!" in line:
                return "early quit!"
    return "got to the end!"

If you were relying on an explicit f=open(filename,…) and a matching
f.close() to close the file, the early return in that loop would bypass
it (or you would have to remember to do the f.close() at the early
return, tedious and accidednt prone).

Cameron Simpson

1 Like