πŸ“„ 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 dataread 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:

Mode                                                              USE

r                                                                     Read (default mode)

w                                                                   Write (overwrites existing file)

a                                                                     Append (adds to end of file)

x                                                                    Create a file (if it doesn't exist)

rb                                                                     Read binary

wb                                                                    Write binary


πŸ“– Reading from a File

Let’s say we have a file called sample.txt with this content:

                Hello, welcome to PythonFunZone!
                                                      Learning Python is fun.                                                          ✅ Code:

                                    file = open("sample.txt", "r")
                                        content = file.read()
                                         print(content)
                                         file.close()

Don’t forget to close the file after you're done!

✍️ 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, and x define 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

Popular posts from this blog

Welcome to Python Fun Zone: Learn, Code, Build!

Day 1: Getting Started with Python – A Friendly Introduction for Beginners

Day 2: Variables and Data Types – The Building Blocks of Python 🐍