Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #196398

Re: Best use of "open" context manager

From Rob Cliffe <rob.cliffe@btinternet.com>
Newsgroups comp.lang.python
Subject Re: Best use of "open" context manager
Date 2024-07-07 22:22 +0100
Message-ID <mailman.13.1720391145.2981.python-list@python.org> (permalink)
References <954c4ca8-cf37-4482-a1be-46d39cb503f9@btinternet.com> <ZonqkTYNCiNQRQSv@cskk.homeip.net> <1ed1c4b0-e89c-4dbc-8b16-35aeebce8ee3@btinternet.com>

Show all headers | View raw



On 07/07/2024 02:08, Cameron Simpson wrote:
> On 06Jul2024 11:49, Rob Cliffe <rob.cliffe@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Best use of "open" context manager Rob Cliffe <rob.cliffe@btinternet.com> - 2024-07-07 22:22 +0100

csiph-web