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


Groups > comp.lang.python > #196403

Re: Best use of "open" context manager

From Cameron Simpson <cs@cskk.id.au>
Newsgroups comp.lang.python
Subject Re: Best use of "open" context manager
Date 2024-07-08 09:02 +1000
Message-ID <mailman.18.1720393364.2981.python-list@python.org> (permalink)
References <1ed1c4b0-e89c-4dbc-8b16-35aeebce8ee3@btinternet.com> <Zoseju8zFLxM-s4r@cskk.homeip.net>

Show all headers | View raw


On 07Jul2024 22:22, Rob Cliffe <rob.cliffe@btinternet.com> wrote:
>>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.

No. You're right, remove 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.

This astounds me. Code snippet to demo this?

Here's a test script which I've just run now:

     FileName = 'foo.txt'
     try:
       f = open(FileName)
     except FileNotFoundError:
       print(f"File {FileName} not found")
       sys.exit()
     with f:
       for line in f:
         print("line:", line.rstrip())

Here's the foo.txt file:

     here are
     some lines of text

Here's the run:

     % python3 p.py
     line: here are
     line: some lines of text

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


Thread

Re: Best use of "open" context manager Cameron Simpson <cs@cskk.id.au> - 2024-07-08 09:02 +1000

csiph-web