Jul-04-2022, 03:58 AM
(This post was last modified: Jul-04-2022, 03:58 AM by deanhystad.)
This creates a context where the file is open.
with open(filename, 'w') as file: file.write('text')The file only remains open while in this context. The context ends when you leave the code block. You leave the code block when you de-indent.
def func(arg): # Assumes caller's context. So file still open. pass with open(filename, 'w') as file: file.write('text') # File is still open func(file) # Called function executes in current context. # File is still open # De-indent ends block of code. File is closedIf you have a lot of code that must execute with the file open I would put that code inside a function and call the function from inside the context manager as shown above.