Sujet : Re: Best use of "open" context manager
De : rob.cliffe (at) *nospam* btinternet.com (Rob Cliffe)
Groupes : comp.lang.pythonDate : 07. Jul 2024, 23:22:49
Autres entêtes
Message-ID : <mailman.13.1720391145.2981.python-list@python.org>
References : 1 2 3
User-Agent : Mozilla Thunderbird
On 07/07/2024 02:08, Cameron Simpson wrote:
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.
Did you test this?
f = open(FileName) as f:
is not legal syntax.
If you omit 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.
I'm using Python 3.11.5.
Best wishes
Rob Cliffe