๐Ÿ Lesson 15: Python File Handling – Read & Write Files

Welcome to Lesson 15! Today we’ll learn about file handling in Python. Files allow your programs to store data permanently, read data from text files, or write results to a file.


⭐ What You Will Learn in This Lesson

  • Open, read, write, and append files
  • Use the with statement for safe file handling
  • Work with files line by line
  • Understand different file modes
  • Save and manage data in your programs

๐Ÿ‘ฅ Who Is This Lesson For?

  • Beginners learning to store program data
  • Students working on projects requiring file input/output
  • Anyone building interactive programs or logs

๐Ÿ“ฆ Opening a File

Use the open() function to work with files. The syntax is:


file = open("example.txt", "mode")
  • "r" – read (default)
  • "w" – write (overwrite)
  • "a" – append (add to end)
  • "r+" – read and write

๐Ÿงฉ 1. Reading Files


# Read entire file
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()

# Read line by line
file = open("example.txt", "r")
for line in file:
    print(line.strip())
file.close()

๐Ÿงฉ 2. Writing Files


file = open("example.txt", "w")
file.write("Hello, Python!\n")
file.write("File handling is fun.")
file.close()

๐Ÿงฉ 3. Appending Files


file = open("example.txt", "a")
file.write("\nAdding a new line.")
file.close()

๐Ÿงฉ 4. Using with Statement

The with statement automatically closes the file for you:


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

with open("example.txt", "a") as file:
    file.write("\nThis is safe and easy!")

๐Ÿงฉ 5. Why File Handling Matters

  • Store data permanently
  • Read configuration or input files
  • Write logs or results
  • Essential for projects, data science, and apps

๐Ÿงช Practice

  1. Create a text file and write your name and age into it.
  2. Read the file and print its content line by line.
  3. Append a new hobby to the file.
  4. Use the with statement to safely read and write files.
  5. Experiment with different file modes (r, w, a, r+) and observe results.

❌ Common Mistakes

  • Forgetting to close files when not using with
  • Overwriting data unintentionally with w mode
  • Trying to read a file that doesn’t exist without try/except

❓ Frequently Asked Questions (FAQ)

1. Can I read large files line by line?

Yes, using a loop: for line in file: reads one line at a time.

2. What happens if I write to a file that already exists?

Using w will overwrite the file. Use a to append instead.

3. Why use the with statement?

It automatically closes the file even if errors occur, making code safer.


➡ Next Lesson

Go to Lesson 16 →

Comments

Popular posts from this blog

How to Install Geany 2.1 on Windows 10/11 (2026) | Step-by-Step Guide

How to Uninstall Bluefish 2.2.19 on Windows 10/11 (2026) | Step-by-Step Guide

How to Install Visual Studio 2026 on Windows 10/11 | Step-by-Step Guide