Introduction
File I/O में हमने सीखा कि file को open कैसे किया जाता है।
अब इस topic में हम सीखेंगे कि file से data कैसे पढ़ते हैं (Reading) और file में data कैसे लिखते हैं (Writing)।
यह दोनों operations practical programming में सबसे ज्यादा use होते हैं।
Reading Files (File पढ़ना)
File से data पढ़ने के लिए file को "r" (read mode) में open किया जाता है।
1. read() method
यह method पूरी file को एक साथ पढ़ता है।
with open("data.txt", "r") as file:
content = file.read()
print(content)
Explanation
यह file का पूरा data एक string के रूप में return करता है।
2. readline() method
यह method file की एक line पढ़ता है।
with open("data.txt", "r") as file:
line = file.readline()
print(line)
3. readlines() method
यह method सभी lines को list के रूप में return करता है।
with open("data.txt", "r") as file:
lines = file.readlines()
print(lines)
Writing Files (File में लिखना)
File में data लिखने के लिए "w" या "a" mode का use किया जाता है।
1. write() method
with open("data.txt", "w") as file:
file.write("Hello Python")
Explanation
यह file में text लिखता है।
अगर file पहले से मौजूद है, तो उसका पुराना data delete हो जाता है।
2. append mode (“a”)
with open("data.txt", "a") as file:
file.write("\nNew Line Added")
Explanation
यह existing file में नया data जोड़ता है, पुराने data को delete नहीं करता।
Writing Multiple Lines
with open("data.txt", "w") as file:
file.write("Line 1\n")
file.write("Line 2\n")
Reading + Writing Example
with open("data.txt", "w") as file:
file.write("Python File Handling")
with open("data.txt", "r") as file:
print(file.read())
Real-life Example: Student record save करना
name = input("Enter name: ")
with open("students.txt", "a") as file:
file.write(name + "\n")
Explanation
यह program student names को file में store करता है।
Real-life Example: File से data पढ़ना
with open("students.txt", "r") as file:
for line in file:
print(line)
Important Difference
| Method | Use |
|---|---|
| read() | पूरी file पढ़ता है |
| readline() | एक line पढ़ता है |
| readlines() | सभी lines list में देता है |
Common mistakes
- “w” mode में file open करके data delete कर देना
- newline (
\n) use न करना - file path गलत देना
Mini Program
with open("data.txt", "w") as file:
file.write("Hello\n")
with open("data.txt", "a") as file:
file.write("World")
with open("data.txt", "r") as file:
print(file.read())
Summary
Reading और Writing Files Python में data को store और retrieve करने का सबसे important तरीका है।
यह concept almost हर real-world application में use होता है।