Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #196389
| From | Cameron Simpson <cs@cskk.id.au> |
|---|---|
| Newsgroups | comp.lang.python |
| Subject | Re: Best use of "open" context manager |
| Date | 2024-07-07 11:08 +1000 |
| Message-ID | <mailman.10.1720315042.2981.python-list@python.org> (permalink) |
| References | <954c4ca8-cf37-4482-a1be-46d39cb503f9@btinternet.com> <ZonqkTYNCiNQRQSv@cskk.homeip.net> |
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.
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Best use of "open" context manager Cameron Simpson <cs@cskk.id.au> - 2024-07-07 11:08 +1000
csiph-web