Sujet : Re: Best use of "open" context manager
De : ram (at) *nospam* zedat.fu-berlin.de (Stefan Ram)
Groupes : comp.lang.pythonDate : 06. Jul 2024, 13:46:33
Autres entêtes
Organisation : Stefan Ram
Message-ID : <file-20240706124604@ram.dialup.fu-berlin.de>
References : 1
Rob Cliffe <
rob.cliffe@btinternet.com> wrote or quoted:
try:
with open(FileName) as f:
except FileNotFoundError:
print(f"File {FileName} not found")
sys.exit()
else: # or "finally:"
for ln in f:
print("I do a lot of processing here")
# Many lines of code here .....
but this of course does not work because by the time we get to "for ln
in f:" the file has been closed so we get
ValueError: I/O operation on closed file
try:
f = open( FileName )
except FileNotFoundError:
print( f"File {FileName} not found" )
sys.exit()
else:
with f:
# put this into a separate function if it gets too long here.
for ln in f:
print( "I do a lot of processing here" )
# Many lines of code here .....