Closing a File (फाइल बंद करना) :-
Python में किसी file पर सभी आवश्यक operations पूरे होने के बाद उसे बंद करने की प्रक्रिया को Closing a File कहते हैं।
File को बंद करने के लिए close() method का उपयोग किया जाता है। File बंद करने से उससे जुड़े system resources को release करने में मदद मिलती है।
English:
Closing a file is the process of ending access to an opened file after completing all the required operations.
Python uses the close() method to close a file and release its associated system resources.
Syntax - file_object.close()
यहाँ file_object उस variable का नाम है जिसमें open() से प्राप्त file object store किया गया है।
Example (उदाहरण)-
file = open("student.txt", "w", encoding="utf-8")
file.write("Welcome to Python")
file.close()
print("File Closed Successfully")
Output:
File Closed Successfully
Explanation (व्याख्या):
open() function से student.txt file open की गई।
"w" mode का उपयोग data लिखने के लिए किया गया।
write() method से file में text लिखा गया।
close() method से file बंद कर दी गई।
print() statement से message display किया गया।
Checking Whether a File Is Closed -
Python में closed attribute का उपयोग करके check कर सकते हैं कि file open है या बंद।
Example:
file = open("demo.txt", "w")
print(file.closed)
file.close()
print(file.closed)
Output:
False
True
Explanation:
File open होने पर file.closed का value False होता है।
File close होने पर file.closed का value True हो जाता है।
Important Points (महत्वपूर्ण बातें)
close() एक file object method है।
इसका उपयोग open file को बंद करने के लिए किया जाता है।
File बंद होने के बाद उस पर reading या writing करने की कोशिश करने पर ValueError आ सकता है।
close() method सामान्यतः None return करता है।
File को बंद करना अच्छी programming practice है।
with statement का उपयोग करने पर file automatically close हो जाती है।