Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #196389 > unrolled thread
| Started by | Cameron Simpson <cs@cskk.id.au> |
|---|---|
| First post | 2024-07-07 11:08 +1000 |
| Last post | 2024-07-07 11:08 +1000 |
| Articles | 1 — 1 participant |
Back to article view | Back to comp.lang.python
This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by
below is the oldest one visible, not the original post.
Re: Best use of "open" context manager Cameron Simpson <cs@cskk.id.au> - 2024-07-07 11:08 +1000
| From | Cameron Simpson <cs@cskk.id.au> |
|---|---|
| Date | 2024-07-07 11:08 +1000 |
| Subject | Re: Best use of "open" context manager |
| Message-ID | <mailman.10.1720315042.2981.python-list@python.org> |
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 top | Article view | comp.lang.python
csiph-web