Interview question
Why should you use the 'with' statement when working with files? Files के साथ काम करते समय 'with' statement क्यों use करना चाहिए?
Answer
The 'with' statement guarantees the file is closed automatically, even if an exception occurs, preventing resource leaks and file corruption from unclosed handles.
# WITHOUT 'with' - manual close required, easy to forget on exceptions
f = open('data.txt', 'r')
data = f.read()
result = 10 / 0 # exception occurs here
f.close() # NEVER REACHED - file stays open, resource leak
# WITH 'with' - close is guaranteed automatically
with open('data.txt', 'r') as f:
data = f.read()
result = 10 / 0 # exception occurs
# f.close() is STILL called automatically as the exception propagates
print(f.closed) # True - confirmed closed even though the exception interrupted execution
# Multiple files in one 'with' statement
with open('input.txt') as infile, open('output.txt', 'w') as outfile:
outfile.write(infile.read().upper())
# both files closed automatically
# Why it matters at scale: too many open file handles can hit OS limits
for i in range(10000):
with open(f'file_{i}.txt', 'w') as f: # each one properly closed
f.write('data')
# vs forgetting to close in a loop - could exhaust file descriptor limits'with' statement यह guarantee करता है कि file automatically close हो, भले ही exception आए, resource leaks और file corruption से बचाता है।
# 'with' के बिना - manual close, exception में भूलना आसान
f = open('data.txt', 'r')
data = f.read()
result = 10 / 0 # exception
f.close() # कभी नहीं पहुंचता - file खुली रह जाती है
# 'with' के साथ - close guaranteed
with open('data.txt', 'r') as f:
data = f.read()
result = 10 / 0
# f.close() automatically call होता है
print(f.closed) # True
# एक with में multiple files
with open('input.txt') as infile, open('output.txt', 'w') as outfile:
outfile.write(infile.read().upper())
# दोनों automatically close हो जाती हैंWas this answer clear?