π Day 13 – File Handling in Python
In the previous blog, we explored how to organize our Python code using modules and packages.
Now imagine this — you're building an app and need to save user data, read a config file, or maybe log errors. For all that, you need File Handling.
Let’s understand how we can work with files using Python in a very simple and practical way.
π Opening a File in Python
Python gives us a built-in function called open() to work with files.
π Syntax:
file = open("filename.txt", "mode")
"filename.txt"– name of the file you want to open"mode"– how you want to open the file: read, write, append, etc
File Modes in Python:
π Reading from a File
sample.txt with this content:✍️ Writing to a File
Now let’s try writing to a file:
file = open("notes.txt", "w")
file.write("Today I learned about file handling in Python.")
file.close()
This will create notes.txt if it doesn't exist, or overwrite it if it does.
➕ Appending to a File
If you don’t want to erase the file and just add new lines, use append mode (a):
file = open("notes.txt", "a")
file.write("\nAppending a second line to the file.")
file.close()
✅ A Better Way – Using with
There’s a cleaner way to work with files using with.
You don’t need to manually close the file — Python does it for you.
with open("data.txt", "r") as file:
content = file.read()
print(content)
π Real-World Example
Let's say you're building a small app and want to log every action your user takes.
def log_action(action):
with open("log.txt", "a") as log_file:
log_file.write(action + "\n")
log_action("User logged in")
log_action("User uploaded a file")
Just like that, you've created a basic logging system using file handling!
π§ Quick Recap
-
Use
open()to read/write files -
Always close the file (or use
with) -
Modes like
r,w,a, andxdefine how file is opened -
Real-life use: storing data, logs, reports, etc.
π― Practice Task
-
Create a file called
diary.txt -
Write today’s date and what you learned in Python
-
Run the program multiple times and append entries
π What’s Next?
In the next blog, we’ll explore Exception Handling — what happens when errors pop up in your code and how to manage them gracefully.
See you there! π
Keep learning, keep building π§ π»
Keep this in Mind:
"Every piece of data has a story. File handling in Python is how we let that story unfold."

Comments
Post a Comment