[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

close() the file when opening "with"?

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.


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