Skip to content
ComputerCS
Start learning

Python Programming · Lesson 2.9.1.4–2.9.1.6

File Handling: Reading, Writing and Appending

Explore reading and writing text files, choosing file modes, using context managers and handling structured data safely.

01

Learning objectives

  • Explain why programs persist data in files rather than keeping everything in memory.
  • Read and write text files using open and context managers.
  • Distinguish read, write and append modes and describe their effects.
  • Handle file paths, encoding and malformed input deliberately.
02

Lesson notes

A variable normally exists only while the program is running. A file stores information beyond one execution, allowing a program to reload user settings, reports or records later. A file has a path, a format and permissions. Text files contain characters; binary files contain bytes and require an appropriate format or decoder.

Python opens files with open(path, mode, encoding). Read mode r expects an existing file, write mode w creates or truncates a file, and append mode a adds to the end. Choose the mode deliberately: opening an important file in w can destroy its previous contents. UTF-8 is a common text encoding and should be specified when portability matters.

A context manager is the safest normal pattern: with open(...) as file: ... . The with statement guarantees that the file is closed when the block exits, including when an exception occurs. read() loads content, readline() reads one line, and iteration over a file processes it line by line without loading the entire file into memory.

Robust file processing validates input and handles expected failures such as FileNotFoundError, PermissionError and UnicodeDecodeError. Keep file data separate from trusted program logic; never assume a CSV field is numeric just because it usually contains a number. For larger structured data, use a suitable parser rather than splitting complex formats by hand.

03

Worked code examples

Worked example

Path offers a readable cross-platform interface for common file operations. The example creates a temporary file, reads it, then removes it.

from pathlib import Path
path = Path("notes.txt")
path.write_text("Nerdlyy\nComputer Science", encoding="utf-8")
content = path.read_text(encoding="utf-8")
print(content.splitlines())
path.unlink()
Output
['Nerdlyy', 'Computer Science']
04

Key terminology

Persistence

Keeping information after a program or device session ends.

File mode

The access behaviour requested when opening a file, such as read, write or append.

Context manager

A construct that manages setup and cleanup around a block, commonly used with files.

Encoding

A mapping between text characters and stored bytes, such as UTF-8.

05

Common misconceptions

Common mistake

Opening a file in write mode preserves the existing contents.

Correct understanding

Mode w truncates an existing file; use append mode or read-modify-write when preservation is required.

Common mistake

A file always closes automatically after every read call.

Correct understanding

Use a with statement so the file is closed reliably when the block ends.

06

Check your understanding

1. Which mode appends new text without truncating existing content?

2. Why is with open(...) preferred?

3. What is UTF-8?

NERDLYY · FEEDBACK

Help shape Nerdlyy

Your feedback goes directly to the team. We read every submission.

No reply needed — you can send feedback without sharing contact details.