Important Notice:

Opening and Closing a File in Python

Opening and Closing a File in Python

5 views 1 min read

Opening and Closing a File in Python :-

Opening a File (फाइल खोलना) -
Python में किसी file को पढ़ने, लिखने या उसमें data जोड़ने के लिए file को open करना आवश्यक होता है। File खोलने के लिए Python के built-in open() function का उपयोग किया जाता है।
 
File open होने पर Python एक file object देता है, जिसकी सहायता से हम file पर विभिन्न operations कर सकते हैं।
 
English 
Opening a file is the process of making a file available to a Python program for reading, writing, or other file operations. Python uses the built-in open() function to open a file.
 
Syntax -
file_object = open("filename", "mode")
 
Explanation:
  • file_object: File object को store करने वाला variable.

  • open(): File खोलने वाला built-in function.

  • "filename": File का नाम या path.

  • "mode": File किस उद्देश्य से खोली जाएगी, जैसे reading या writing.

 

Example 1: Opening a File for Reading
 
file = open("student.txt", "r")
print(file)
file.close()

 

Explanation:
 
इस उदाहरण में student.txt को read mode में खोला गया है। यह file पहले से मौजूद होनी चाहिए।
यदि file मौजूद नहीं है, तो Python FileNotFoundError देगा। print(file) file object का representation दिखाता है, जिसका सटीक output Python environment के अनुसार अलग हो सकता है।
 
Example 2: Opening a File for Writing
 
file = open("student.txt", "w")
file.write("Hello Python")
file.close()

 

Explanation:
  • "w" का अर्थ write mode है।

  • यदि file मौजूद नहीं है, तो Python उसे बनाने का प्रयास करता है।

  • यदि file पहले से मौजूद है, तो उसकी पुरानी सामग्री मिट जाती है।

  • write() file में text लिखता है।

  • close() file बंद करता है।

Related Notes