Master File Handling in Python πŸ”₯ | with-as, Modes Explained! #16 || Python ka Pitara || DeathCode - DeathCode

πŸ§’ 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 hai
  • readlines() β†’ 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 πŸš€

Β© 2024 DeathCode. All Rights Reserved.