Python File Handling in Hindi | पाइथन में फाइल कैसे पढ़ें और लिखें?
📘 Chapter 8: फ़ाइल हैंडलिंग (File Handling in Python)
Python में हम टेक्स्ट फाइल को पढ़ सकते हैं, उसमें कुछ लिख सकते हैं या नई फाइल बना सकते हैं। इसके लिए Python में कुछ खास फंक्शन दिए गए हैं जैसे – open()
, read()
, write()
, close()
आदि।
🔹 File खोलना (open):
open()
फंक्शन से फाइल को खोला जाता है।
file = open("example.txt", "r") # पढ़ने के लिए
file = open("example.txt", "w") # लिखने के लिए (purani content मिट जाएगी)
file = open("example.txt", "a") # जोड़ने के लिए
🔹 File पढ़ना (read):
file = open("example.txt", "r")
print(file.read())
file.close()
🔹 कुछ शब्द या लाइन पढ़ना:
print(file.read(10)) # 10 characters
print(file.readline()) # एक लाइन
🔹 File में लिखना (write):
file = open("example.txt", "w")
file.write("Hello Python\nWelcome to File Handling!")
file.close()
🔹 File में लाइन जोड़ना (append):
file = open("example.txt", "a")
file.write("\nThis is a new line.")
file.close()
🔹 with स्टेटमेंट से फाइल ऑटोमेटिक क्लोज करना:
with open("example.txt", "r") as file:
data = file.read()
print(data)
🔹 फाइल हटाना (delete file):
import os
os.remove("example.txt")
📌 इस चैप्टर में आपने सीखा:
- Python में फाइल को कैसे खोला जाता है
- read(), write(), और append() का प्रयोग
- with स्टेटमेंट से फाइल को संभालना
- os module से फाइल को हटाना
➡️ अगला चैप्टर:
Chapter 9: Exception Handling – पाइथन में error को पकड़ने और संभालने का तरीका
Post a Comment
0 Comments