open, close

Peter Otten __peter__ at web.de
Sat Aug 31 10:37:23 EDT 2019


Manfred Lotz wrote:

> Hi there,
> This is a beginner question.
> 
> I learned that
> 
> with open("foo.txt") as f:
>         lines = f.readlines()
> 
> using the with-construct is the recommended way to deal with files
> making sure that close() always happens.
> 
> However, I also could do:
> 
> lines = open("foo.txt").readlines()
> 
> I have to admit that I'm not sure if in case something bad happens a
> close() is done implicitly as in the first example.
> 
> 
> Could I use the latter as a substitute for the with-construct? What are
> the recommendations of the experts?

Always using 

with open(...) ...

is a good habit to get into. If you need to read all lines of a file very 
often write a helper function:

def readlines(filename):
    with open(filename) as f:
        return f.readlines()

That way you can write

lines = readlines("foo.txt")

which saves even more typing and still closes the file deterministically.




More information about the Python-list mailing list