Best use of "open" context manager

Rob Cliffe rob.cliffe at btinternet.com
Sun Jul 7 17:22:49 EDT 2024



On 07/07/2024 02:08, Cameron Simpson wrote:
> 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.
Did you test this?
     f = open(FileName) as f:
is not legal syntax.
If you omit the "as f:"
it's legal, but doesn't work (trying to access the file after "with f" 
raises the same
     ValueError: I/O operation on closed file.
I'm using Python 3.11.5.

Best wishes
Rob Cliffe


More information about the Python-list mailing list