Important Notice:

Writing Using with Statement

Writing Using with Statement

4 views 2 min read

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.

Syntax:
 
with open("filename.txt", "w", encoding="utf-8") as file:
    file.write("Hello Python")
 
Example 1: with Statement से एक String लिखना
 
with open("demo.txt", "w", encoding="utf-8") as file:
    file.write("Hello Python")

File Content:

Hello Python

Explanation:

  • with Statement File को Open करता है।

  • as file File Object को file नाम देता है।

  • write() Data को File में Write करता है।

  • Block समाप्त होने पर File Automatically Close हो जाती है।

Example 2: with Statement से Multiple Lines लिखना

with open("demo.txt", "w", encoding="utf-8") as file:
    file.write("Hello Python\n")
    file.write("Welcome to File Handling\n")
    file.write("Python is Easy")

File Content:

Hello Python
Welcome to File Handling
Python is Easy
 
Example 3: with Statement के साथ writelines()
 
data = [
    "Apple\n",
    "Mango\n",
    "Banana\n"
]

with open("fruits.txt", "w", encoding="utf-8") as file:
    file.writelines(data)

File Content:

Apple
Mango
Banana
 
Example 4: File Automatically Close होने की जाँच
 
with open("demo.txt", "w", encoding="utf-8") as file:
    file.write("Hello Python")
    print(file.closed)

print(file.closed)

Output:

False
True

Explanation:

  • with Block के अंदर File Open रहती है, इसलिए file.closed का Output False आता है।

  • Block समाप्त होने के बाद File Automatically Close हो जाती है।

  • इसलिए बाहर file.closed का Output True आता है।

Advantages of Using with Statement

  1. File Automatically Close हो जाती है।

  2. अलग से close() लिखने की आवश्यकता नहीं होती।

  3. File Handling अधिक सुरक्षित और आसान होती है।

  4. Exception आने पर भी File Properly Close होती है।

  5. Code छोटा और व्यवस्थित रहता है।

Related Notes