Usin with Statement in Python :-
Python में with statement का उपयोग file को सुरक्षित और आसान तरीके से handle करने के लिए किया जाता है। जब हम with open() का उपयोग करके file खोलते हैं, तो with block समाप्त होने पर file automatically close हो जाती है।
इसमें अलग से close() method लिखने की आवश्यकता नहीं होती।
English:
The with statement is used to handle files safely and efficiently in Python. When a file is opened using with open(), it is automatically closed when the with block ends.
There is no need to call the close() method explicitly.
2. Syntax-
with open("filename", "mode") as file:
# File operations
Explanation
with – Context management statement है।
open() – File को open करता है।
"filename" – File का नाम या path है।
"mode" – File खोलने का mode है।
as file – File object को file variable में store करता है।
Indented block – इसमें file से संबंधित operations किए जाते हैं।
3. Example 1: Writing Data Using with Statement
Program:
with open("student.txt", "w", encoding="utf-8") as file:
file.write("Name: Rahul\n")
file.write("Course: O Level\n")
file.write("Marks: 85")
print("Data Written Successfully")
Output:
Data Written Successfully
student.txt File Content:
Name: Rahul
Course: O Level
Marks: 85
Explanation (व्याख्या)
with open() से student.txt file open की गई।
"w" mode का उपयोग writing के लिए किया गया।
write() method से file में data लिखा गया।
जैसे ही with block समाप्त हुआ, file automatically close हो गई।
print() statement ने message display किया।
4. Example 2: Reading Data Using with Statement
Program:
with open("student.txt", "r", encoding="utf-8") as file:
data = file.read()
print(data)
Output:
Name: Rahul
Course: O Level
Marks: 85
Explanation
File को "r" mode में open किया गया।
read() method से पूरा data पढ़ा गया।
print() से data display किया गया।
with block समाप्त होने पर file automatically close हो गई।
5. Example 3: Checking File Status Using closed
Program:
with open("demo.txt", "w") as file:
file.write("Hello Python")
print(file.closed)
print(file.closed)
Output:
False
True
Explanation
with block के अंदर file open रहती है, इसलिए False मिलता है।
with block समाप्त होने पर file close हो जाती है, इसलिए True मिलता है।