I help startups and teams build production-ready apps with Django, Flask, and FastAPI.
Let’s Talk →I'm always excited to take on new projects and collaborate with innovative minds.
No 7 Street E, Federal Low-cost Housing Estate, Kuje, Abuja 903101, Federal Capital Territory
Python Tutorial for Beginners (Lesson 13): Learn Python file handling – how to open, read, write, append, and safely manage files using with open() and error handling.
Welcome back to the Python Tutorial Series for Beginners! 🎉
In Lesson 12, we explored Modules and Packages and learned how to organize code and use external libraries.
Now in Lesson 13, we’ll dive into File Handling – an essential part of programming that allows you to read, write, and manage files on your computer.
By the end of this lesson, you’ll understand:
read, readline, readlines)with open() (context managers)👉 File handling lets your programs store data permanently.
Examples in real life:
The built-in open() function is used:
Common modes:
"r" → Read (default)"w" → Write (overwrites file)"a" → Append (adds to file)"b" → Binary mode (for images, etc.)Always remember to close the file:
Assume example.txt contains:
👉 Output:
👉 Output: Hello
👉 Output:
👉 Writing will overwrite existing content.
👉 Now example.txt contains:
👉 Use "a" mode to keep existing content and add new lines.
with open() (Best Practice)Instead of manually opening and closing, use a context manager:
✅ The file automatically closes after the block.
"example.txt".Sometimes files don’t exist. Handle safely with try...except:
👉 Output:
✅ Writing Logs
✅ Storing User Input
✅ Reading Config Files
Try these in a new file (lesson13.py):
notes.txt and write three lines into it.notes.txt saying “Python makes file handling easy!”.try...except to handle the case where a file does not exist.In this lesson, you learned:
✅ How to open and close files in Python
✅ Reading (read, readline, readlines) and writing to files
✅ Difference between write (w) and append (a) modes
✅ Best practice with with open()
✅ Error handling with missing files
Next up: Lesson 14 – Error Handling & Exceptions in Python ⚠️
I'm Kingsley Odume, a Django, Flask, and FastAPI developer with experience building SaaS platforms, APIs, and modern web apps. If you're a recruiter or business owner looking for a reliable software developer, let's connect!
🚀 Hire MeYour email address will not be published. Required fields are marked *