Best use of "open" context manager

Cameron Simpson cs at cskk.id.au
Sat Jul 6 21:08:33 EDT 2024


On 06Jul2024 11:49, Rob Cliffe <rob.cliffe at btinternet.com> wrote:
>try:
>    f = open(FileName) as f:
>    FileLines = f.readlines()
>except FileNotFoundError:
>    print(f"File {FileName} not found")
>    sys.exit()
># I forgot to put "f.close()" here -:)
>for ln in File Lines:
>        print("I do a lot of processing here")
>        # Many lines of code here .....

What about this:

     try:
         f = open(FileName) as f:
     except FileNotFoundError:
         print(f"File {FileName} not found")
         sys.exit()
     with f:
         ... process the lines here ...

Remember, the `open()` call returns a file object _which can be used as 
a context manager_. It is separate from the `with` itself.


More information about the Python-list mailing list