👋 Work With Me

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.

Address

No 7 Street E, Federal Low-cost Housing Estate, Kuje, Abuja 903101, Federal Capital Territory

Social Links

Tutorials

Python Tutorial Series – Lesson 13: File Handling in Python

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.

Python Tutorial Series – Lesson 13: File Handling in Python

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:

  • Opening and closing files
  • Reading files (read, readline, readlines)
  • Writing and appending to files
  • Working with file paths
  • Using with open() (context managers)
  • Handling file errors safely
  • Beginner exercises

🔹 1. Why File Handling Matters

👉 File handling lets your programs store data permanently.

Examples in real life:

  • Saving user data in a text file
  • Logging program activity
  • Reading CSV files for data analysis
  • Writing results to files instead of printing them only

🔹 2. Opening a File

The built-in open() function is used:

 
# open(filename, mode)
file = open("example.txt", "r")

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:

 
file.close() 

🔹 3. Reading from a File

Assume example.txt contains:

 
Hello World
Python is awesome

Read entire content:

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

👉 Output:

 
Hello World
Python is awesome

Read only first 5 characters:

 
file = open("example.txt", "r")
print(file.read(5))
file.close()

👉 Output: Hello

Read line by line:

 
file = open("example.txt", "r")
print(file.readline())   # first line
print(file.readline())   # second line
file.close()

Read all lines into a list:

 
file = open("example.txt", "r")
lines = file.readlines()
print(lines)
file.close()

👉 Output:

 
['Hello World\n', 'Python is awesome\n'] 

🔹 4. Writing to a File

👉 Writing will overwrite existing content.

 
file = open("example.txt", "w")
file.write("New content here\n")
file.write("Another line\n")
file.close()

👉 Now example.txt contains:

 
New content here
Another line

🔹 5. Appending to a File

👉 Use "a" mode to keep existing content and add new lines.

 
file = open("example.txt", "a")
file.write("This line is appended.\n")
file.close()

🔹 6. Using with open() (Best Practice)

Instead of manually opening and closing, use a context manager:

 
with open("example.txt", "r") as file:
   content = file.read()
   print(content)

✅ The file automatically closes after the block.


🔹 7. Working with File Paths

  • If the file is in the same folder → just use "example.txt".
  • If in another folder:
 
file = open("data/example.txt", "r") 
  • For absolute paths (Windows):
 
file = open("C:\\Users\\User\\Documents\\example.txt", "r") 

🔹 8. Handling File Errors

Sometimes files don’t exist. Handle safely with try...except:

 
try:
   with open("notfound.txt", "r") as file:
       content = file.read()
       print(content)
except FileNotFoundError:
   print("File not found!")

👉 Output:

 
File not found! 

🔹 9. Real-World Use Cases

Writing Logs

 
with open("log.txt", "a") as log:
   log.write("User logged in\n")

Storing User Input

 
name = input("Enter your name: ")
with open("users.txt", "a") as f:
   f.write(name + "\n")
 

Reading Config Files

 
with open("config.txt", "r") as cfg:
   settings = cfg.readlines()
   print("Settings:", settings)

🔹 10. Exercises for Beginners

Try these in a new file (lesson13.py):

  1. Create a file named notes.txt and write three lines into it.
  2. Read the file and print each line separately.
  3. Append a new line to notes.txt saying “Python makes file handling easy!”.
  4. Write a program that counts how many lines are in a file.
  5. Use try...except to handle the case where a file does not exist.

🎯 Recap

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 ⚠️

💼 Need a Developer?

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 Me

Python, Python tutorials, Python Beginners series, Python Step-byStep
4 min read
Aug 20, 2025
By Kingsley Odume
Share

Leave a comment

Your email address will not be published. Required fields are marked *

Related posts

Aug 29, 2025 • 3 min read
Step-by-Step: Building a SaaS App with Django + Stripe Payments

Learn how to build a real-world SaaS app with Django and Stripe paymen...

Aug 21, 2025 • 3 min read
Final Wrap-Up: Python Tutorial Series for Beginners

Congratulations on completing the Python Tutorial Series! 🚀 In this w...

Aug 20, 2025 • 4 min read
Final Lesson: Mini Project – Putting It All Together in Python

In this final lesson, we’ll bring all those concepts together in a Min...

Your experience on this site will be improved by allowing cookies. Cookie Policy