open, close

Manfred Lotz ml_news at posteo.de
Sat Aug 31 10:48:51 EDT 2019


On Sat, 31 Aug 2019 16:37:23 +0200
Peter Otten <__peter__ at web.de> wrote:

> 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.

As a Python beginner I started to use with open.. in all cases but was
tempted to use the even shorter one-line way of reading a file.

So, I will continue to use with open... ALWAYS as good habits are very
helpful in life. :-)


> 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.
> 

Good idea.


Thanks to all for your help.

-- 
Manfred





More information about the Python-list mailing list