📁 Python Course in 4 to 6 Weeks – Lesson 11: File Handling in Python
Welcome to Lesson 11 of the Python Course in 4 to 6 Weeks! In this lesson, we’ll explore File Handling – how to read from, write to, and manage files using Python. File operations are essential for real-world applications like saving data, logging, or user-generated content.
✅ What You'll Learn
- How to open and close files in Python
- Reading content from text files
- Writing and appending data to files
- Using
with
statements (context managers) - Handling file errors and exceptions
📂 Opening a File
# open(file, mode)
file = open("data.txt", "r") # "r" = read mode
print(file.read())
file.close()
📝 Writing to a File
file = open("output.txt", "w") # "w" = write mode (overwrites)
file.write("Hello, this is a new file!")
file.close()
➕ Appending to a File
file = open("output.txt", "a") # "a" = append mode
file.write("\nAnother line added!")
file.close()
🔒 Using with
for Safe File Access
with open("data.txt", "r") as file:
content = file.read()
print(content)
# Automatically closes the file
⚠️ Common Mistakes
- ❌ Forgetting to close a file (use
with
instead) - ❌ FileNotFoundError – opening a file that doesn’t exist
- ❌ Wrong file mode (e.g. trying to read in write mode)
🧪 Practice Challenge
Create a Python file named file_logger.py
that:
- Asks the user to input a message
- Appends the message to a file called
log.txt
- Displays the full content of the file after writing
📥 Tools You'll Need
- 🐍 Python: https://www.python.org/downloads/
- 📝 VS Code: https://code.visualstudio.com/
- 🌐 Replit: https://replit.com/languages/python3
📌 Final Words
File handling is a fundamental part of building real-world Python applications. Whether you're saving logs, generating reports, or managing user content, you'll use file operations often. In the next lesson, we’ll look at how to write safer programs using error handling.
🔗 Coming Next:
Lesson 12: Error Handling – Try, Except & Writing Safe Python Code 🛡️