Writing Using with Statement (with Statement से Data लिखना) :-
Python में with Statement का उपयोग करके File में Data Write किया जा सकता है। इसके Block का काम पूरा होने पर File Automatically Close हो जाती है। यदि Block के दौरान कोई Exception आती है, तब भी File Close हो जाती है।
English: The with statement is used to write data into a file. It automatically closes the file when the block exits, even if an exception occurs.
Explanation:
with Statement File को Open करता है।
as file File Object को file नाम देता है।
write() Data को File में Write करता है।
Block समाप्त होने पर File Automatically Close हो जाती है।
Example 2: with Statement से Multiple Lines लिखना
Explanation:
with Block के अंदर File Open रहती है, इसलिए file.closed का Output False आता है।
Block समाप्त होने के बाद File Automatically Close हो जाती है।
इसलिए बाहर file.closed का Output True आता है।
Advantages of Using with Statement
File Automatically Close हो जाती है।
अलग से close() लिखने की आवश्यकता नहीं होती।
File Handling अधिक सुरक्षित और आसान होती है।
Exception आने पर भी File Properly Close होती है।
Code छोटा और व्यवस्थित रहता है।