Interview question
What happens if you don't close a file properly, and how do you check if a file is closed? अगर file सही से close न करें तो क्या होता है, और कैसे check करें file closed है या नहीं?
Answer
Failing to close files can lead to resource leaks, data not being flushed to disk (partial writes), and eventually hitting OS limits on open file handles for long-running programs.
# Checking if a file is closed
f = open('data.txt', 'w')
print(f.closed) # False - still open
f.close()
print(f.closed) # True
# Writing without closing may not flush data to disk immediately
f = open('data.txt', 'w')
f.write('Important data')
# If the program crashes HERE, the write may never reach disk -
# file buffers are often only flushed on close() or explicit flush()
f.close() # now guaranteed to be written
# Manually flushing without closing (useful for logs written over time)
f = open('log.txt', 'w')
f.write('Log entry 1\n')
f.flush() # forces the OS to write buffered data now, file stays open
f.write('Log entry 2\n')
f.close()
# Resource leak example - many open handles without closing
files = []
for i in range(10000):
files.append(open(f'temp_{i}.txt', 'w')) # never closed
# Eventually raises OSError: [Errno 24] Too many open files
# The 'with' statement avoids ALL of these problems automatically
with open('data.txt', 'w') as f:
f.write('Safe data')
# guaranteed closed and flushed here, even on exceptionsFiles सही से close न करने से resource leaks, disk पर data flush न होना (partial writes), और लंबे समय चलने वाले programs में OS की open file handles limit टकराना हो सकता है।
# File closed है या नहीं check करना
f = open('data.txt', 'w')
print(f.closed) # False
f.close()
print(f.closed) # True
# बिना close किए लिखने पर data disk तक तुरंत नहीं पहुंच सकता
f = open('data.txt', 'w')
f.write('Important data')
# यहां crash हो तो data कभी disk पर नहीं पहुंच सकता
f.close() # अब guaranteed लिखा जाएगा
# बिना close किए manually flush करना
f = open('log.txt', 'w')
f.write('Log entry 1\n')
f.flush() # buffered data अभी लिखा जाता है
f.write('Log entry 2\n')
f.close()
# Resource leak उदाहरण
files = []
for i in range(10000):
files.append(open(f'temp_{i}.txt', 'w')) # कभी close नहीं
# आखिर में OSError: Too many open files
# 'with' statement यह सब automatically avoid करता है
with open('data.txt', 'w') as f:
f.write('Safe data')Was this answer clear?