File Handling: Read and Write Data Safely

Introduction

In this chapter, you will learn file handling in Python, including how to read, write, append, and manage text files safely. File operations are a core skill for logs, reports, configuration, and data storage. Once you understand this chapter, your scripts can persist data beyond program runtime.

Prerequisites

  • Python 3.10+ installed
  • Basic understanding of strings, loops, and exception handling
  • Ability to run .py files in terminal or IDE

Why File Handling Matters

Without files, program data is lost when execution ends.

With file handling, you can:

  • store user data
  • save reports
  • load configuration
  • process logs and datasets

1) Open Files with open()

Basic syntax:

python
open(file_path, mode, encoding="utf-8")

Common modes:

  • "r": read (default)
  • "w": write (overwrite)
  • "a": append
  • "x": create new file, fail if exists

Example:

python
# Open file for reading
f = open("notes.txt", "r", encoding="utf-8")
content = f.read()
print(content)
f.close()

with automatically closes files, even if errors happen.

python
# Safe file read
with open("notes.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

Tip

Best Practice

Prefer with open(...) over manual open()/close() to avoid resource leaks.

3) Read File Content

Read Entire File

python
with open("notes.txt", "r", encoding="utf-8") as f:
    data = f.read()
    print(data)

Read One Line

python
with open("notes.txt", "r", encoding="utf-8") as f:
    first_line = f.readline()
    print(first_line)

Read All Lines as List

python
with open("notes.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
    print(lines)

Iterate Line by Line (Memory Friendly)

python
with open("notes.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())

4) Write and Append Files

Write (Overwrite)

python
with open("report.txt", "w", encoding="utf-8") as f:
    f.write("Python learning report\n")
    f.write("Day 1 completed\n")

Append

python
with open("report.txt", "a", encoding="utf-8") as f:
    f.write("Day 2 completed\n")

"w" clears old content; "a" keeps old content and adds new text.

5) File Existence and Exceptions

File operations can fail, so combine with exception handling.

python
try:
    with open("missing.txt", "r", encoding="utf-8") as f:
        print(f.read())
except FileNotFoundError:
    print("File not found.")
except PermissionError:
    print("No permission to access file.")

This keeps your script user-friendly and robust.

6) Real Mini Example: Score Report File

Write student scores to file, then read and print summary.

This pattern is common in export, reporting, and audit logs.

Warning

Be careful with "w" mode.
It overwrites existing content immediately.

7) File Path Tips (Beginner-Friendly)

  • Use relative paths for project-local files
  • Use raw strings for Windows paths, for example r"C:\data\file.txt"
  • Keep consistent encoding (utf-8) for cross-platform safety

Common Beginner Mistakes

Mistake 1: Forgetting to Close File

This can cause file lock or incomplete writes in some environments.

Mistake 2: Using Wrong Mode

Using "w" when intending append will erase existing data.

Mistake 3: Ignoring Encoding

Missing or inconsistent encoding may cause garbled text.

Surprise Practice Challenge

Build a "Daily Study Logger":

  1. Ask user to input today's study topic and minutes
  2. Append one line to study_log.txt
  3. Read all logs and print total study minutes
  4. Handle file-not-found gracefully
  5. Print a summary report in terminal

If you finish this, you can already build simple persistent CLI tools.

FAQ

Should I always use utf-8?

In most modern projects, yes. It avoids many cross-platform text issues.

What is the difference between read() and readlines()?

read() returns one string; readlines() returns a list of lines.

Is line-by-line reading better than read()?

For large files, yes. It is more memory-efficient.

How do I avoid accidentally deleting file content?

Use "a" mode for append, and create backups before overwrite operations.