close() the file when opening "with"?

Peter J. Holzer hjp-python at hjp.at
Sun Jun 14 13:21:23 EDT 2020


On 2020-06-14 10:12:26 -0000, Bischoop wrote:
> So far I learnt "with" closes the file opened therefore "Generally" no
> need to close() file. I'm worry about this "Generally", then close() or
> not?

In some cases you don't want the file to be automatically closed when
you leave the context where you opened it (for example, you might want
to write a function which opens a file, does some checks on it and then
returns the file handle to the caller so that it can read or write the
file). In those cases you can't use "with open ..." and you will have
to close the file in some other fashion (for example, the caller could
be responsible for calling close, or you could write your function as a
context manager and the caller could call it as "with my_open ...")

So, "generally" you want to use open together with "with" (and then the
file will be automatically closed), but sometimes you want to do
soemthing else.

        hp

-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20200614/8fc6dedf/attachment.sig>


More information about the Python-list mailing list