Python File Close

Why Should We Close a File?

When working with files in Python, it is important to close a file after you are done with it. Closing a file ensures:

  • All buffered data is written and saved properly.
  • System resources used by the file (like memory and file handles) are freed.
  • Other programs or processes can access the file safely.
If you don't close a file, it can cause data loss, memory leaks, or locked files.

Python में फाइल के साथ काम करते समय, काम खत्म होने के बाद फाइल को बंद करना ज़रूरी होता है। फाइल बंद करने से निम्न फायदे होते हैं:

  • सभी buffered डेटा सही से लिखा और सहेजा जाता है।
  • फाइल द्वारा उपयोग किए गए सिस्टम संसाधन (जैसे मेमोरी और फाइल हैंडल) मुक्त हो जाते हैं।
  • अन्य प्रोग्राम या प्रक्रियाएं फाइल को सुरक्षित रूप से एक्सेस कर पाती हैं।
अगर फाइल को बंद नहीं किया गया तो डेटा खो सकता है, मेमोरी लीक हो सकती है, या फाइल लॉक हो सकती है।

Examples of File Closing in Python

Example 1: Close a File After Writing

file = open('example.txt', 'w')
file.write('Hello, World!')
file.close()
Output:
Writes 'Hello, World!' to example.txt and closes the file.

Always call close() to ensure data is saved and resources are freed.

close() कॉल करना ज़रूरी है ताकि डेटा सही से सेव हो और संसाधन मुक्त हों।

Example 2: Forgetting to Close Can Cause Data Loss

file = open('example.txt', 'w')
file.write('Data without closing')
# forgot file.close() here!
Output:
Data may not be saved properly if close() is not called.

Without close(), buffered data might not be written to disk immediately.

अगर close() नहीं करेंगे तो buffered डेटा डिस्क पर सही से नहीं लिखा जा सकता।

Example 3: Using with Statement (Automatically Closes)

with open('example.txt', 'w') as file:
    file.write('Auto closed file')
Output:
File is automatically closed after the with block ends.

Using with statement is safer and recommended to handle files.

with स्टेटमेंट फाइल को ऑटोमेटिक बंद करता है, जो सुरक्षित तरीका है।

Example 4: Check If File is Closed

file = open('example.txt', 'w')
file.close()
print(file.closed)
Output:
True

The closed attribute tells if the file is closed.

closed attribute बताता है कि फाइल बंद है या नहीं।

Example 5: Reopen a Closed File

file = open('example.txt', 'w')
file.write('Hello')
file.close()
file = open('example.txt', 'r')
print(file.read())
file.close()
Output:
Hello

You can reopen a file after closing it to read or write again.

फाइल बंद करने के बाद फिर से खोलकर पढ़ा या लिखा जा सकता है।

© 2026 Login Technologies. All rights reserved.

Learn to Code Anytime, Anywhere | Contact Us