Sobes.tech
Junior

How can we guarantee file closure if we do not use the 'with' statement?

sobes.tech AI

Answer from AI

Using a try...finally block. The try block contains file opening and working code. The finally block guarantees that close() is called, even if exceptions occur.

# Open file
file = open('my_file.txt', 'r')
try:
    # Read content
    content = file.read()
    print(content)
finally:
    # Guarantee closing
    file.close()

However, using with is preferred, as it is more idiomatic and concise for working with context managers. with also handles exceptions and guarantees close() is called.