π§ Mastering File Handling in Python β The Real-World Way
Python me file handling ek essential skill haiβchahe aap logs store kar rahe ho, configurations read kar rahe ho ya data process kar rahe ho. Har automation ya real-world project kisi na kisi file operation pe depend karta hi hai.
Is guide me hum cover karenge: open()
, different file modes, read/write
, with-as
, common use-cases, real-world tricks, and some next-level tips jo aapko real Python dev banayenge.
open()
β File Handling Ka Gateway
π f = open("data.txt", "r")
open()
function ka use hota hai kisi file ko access karne ke liye. Ye function do major cheeze leta hai:
- Filename: jise access karna hai
- Mode: read, write, append, etc.
Ye bilkul waise hi hai jaise kisi database se connection establish karna.
π File Modes β Poora Control Aapke Haath Me
Mode | Meaning | Notes |
---|---|---|
r |
Read | Default, file must exist |
w |
Write | Overwrites if file exists |
a |
Append | Adds to end if file exists |
x |
Create | Fails if file exists |
b |
Binary mode | Used for images/videos/files |
t |
Text mode (default) | Used for text files |
Example:
f = open("log.txt", "a") # append mode
π Reading Files β Lines, Entire Text, Selective Access
f = open("data.txt", "r")
content = f.read()
print(content)
f.close()
Alternatives:
readline()
β ek line padhta haireadlines()
β list of all lines
Tip: Always close file after use using f.close()
or better use with-as
block.
with open()
β Safe & Clean File Handling
π with open("data.txt", "r") as f:
data = f.read()
print(data)
with
block ensures file properly close ho jaye, even if error aaye.
Real-World Use:
- Logs read karna
- Configuration load karna
- Data parsing
βοΈ Writing & Appending Data
with open("log.txt", "w") as f:
f.write("Starting log...\n")
Append mode:
with open("log.txt", "a") as f:
f.write("Next log line\n")
Useful for:
- Saving user inputs
- Creating daily logs
- Exporting reports
β»οΈ Real-World Use Cases
- Chat logs save karna:
with open("chat.txt", "a") as f:
f.write(f"User: {input()}\n")
- Read config file:
with open("config.ini", "r") as f:
for line in f:
if "username" in line:
print(line)
- CSV file me data save karna:
with open("data.csv", "w") as f:
f.write("Name,Score\n")
f.write("Alice,90\n")
π Bonus Tips
- Use
os.path.exists("file")
to check before accessing - Use
try-except
around file ops for safety - Always handle encoding (
utf-8
) for non-English data
with open("bio.txt", "r", encoding="utf-8") as f:
print(f.read())
Aapne ab tak seekha file access, read/write, append, safe handling and real-world use. Next step? In sabka use real projects me karo. Try making:
- Note app (text based)
- Log parser
- CSV export automation
Milte hai agle part mein, Stay tuned, and code smart π