Skip to content
Computer Science · Class 12 · Computational Thinking and Programming · Term 1

Text File Handling: Read and Write Modes

Students will learn to open, read from, and write to text files, understanding file modes and basic file operations.

CBSE Learning OutcomesCBSE: Computational Thinking and Programming - File Handling - Class 12

About This Topic

File handling is a key skill in Python programming for Class 12 students. It allows them to manage data persistently beyond programme execution. In this topic, students learn to open files in read ('r'), write ('w'), append ('a'), and read-write ('r+') modes. Each mode has specific implications: 'r' for reading only, 'w' for overwriting content, 'a' for adding at the end, and 'r+' for both reading and writing from the start. Students practise using open(), read(), write(), and close() functions to handle text files effectively.

Basic operations include reading entire files with read(), line-by-line with readline(), or all lines with readlines(). Writing involves write() for strings or writelines() for lists. Proper file closing prevents resource leaks and data corruption. Students construct scripts to read specific lines and evaluate why closing files matters, aligning with CBSE standards on computational thinking.

Active learning benefits this topic by letting students experiment with real files, debug errors like FileNotFoundError, and see immediate outputs, which builds confidence and deepens understanding of file modes.

Key Questions

  1. Explain the different modes for opening a file in Python and their implications.
  2. Construct a Python script to read specific lines from a text file.
  3. Evaluate the importance of closing files after operations are complete.

Learning Objectives

  • Compare the outcomes of writing to a file in 'w' mode versus 'a' mode by analyzing the resulting file content.
  • Construct a Python script to read specific lines from a text file based on line numbers.
  • Evaluate the necessity of closing a file handle by explaining potential data loss or corruption scenarios.
  • Demonstrate the use of 'r+', 'w', and 'a' file modes to perform different operations on a text file.

Before You Start

Introduction to Python Programming

Why: Students need basic knowledge of Python syntax, variables, and data types to understand file operations.

Basic Data Types (Strings, Lists)

Why: File content is often read into strings or lists, and written from these data types.

Key Vocabulary

File ModeA code indicating the purpose for which a file is opened, such as reading ('r'), writing ('w'), or appending ('a').
Read Mode ('r')Opens a file for reading only. The file pointer is placed at the beginning. An error occurs if the file does not exist.
Write Mode ('w')Opens a file for writing. Creates the file if it does not exist, or truncates (empties) the file if it exists.
Append Mode ('a')Opens a file for appending. The file pointer is at the end of the file if it exists. Creates the file if it does not exist.
Read-Write Mode ('r+')Opens a file for both reading and writing. The file pointer is at the beginning. The file is not truncated.

Watch Out for These Misconceptions

Common MisconceptionFiles can be read and written in the same mode without issues.

What to Teach Instead

Modes like 'r' are read-only; use 'r+' or 'w+' for both, but 'r+' starts at beginning while 'a+' appends.

Common MisconceptionForgetting to close files has no effect.

What to Teach Instead

Unclosed files lock resources, risk data loss, and cause errors in concurrent operations; always use close() or with statement.

Common Misconceptionread() always reads the entire file.

What to Teach Instead

read() without arguments reads all; use read(n) for n bytes or readline() for one line.

Active Learning Ideas

See all activities

Real-World Connections

  • Software developers use file handling to store user preferences, game saves, and application logs in applications like VS Code or a mobile game.
  • Data analysts in market research firms read data from CSV files to analyze sales trends or customer feedback, often appending new data to existing reports.
  • System administrators manage server configuration files, reading settings and writing updates to files like `/etc/nginx/nginx.conf` to modify web server behaviour.

Assessment Ideas

Quick Check

Present students with three code snippets, each opening a file in 'r', 'w', and 'a' mode respectively. Ask them to predict the content of the file after each snippet executes and explain their reasoning.

Exit Ticket

Provide students with a small text file. Ask them to write a Python command to read the third line of the file and another command to append the text 'End of file.' to it. They should also write one sentence on why `file.close()` is important.

Discussion Prompt

Pose the scenario: 'You have a log file that needs to record every error that occurs. Which file mode would you use and why? What could happen if you forget to close the file after writing?' Facilitate a class discussion on their answers.

Frequently Asked Questions

What are the main file opening modes in Python?
Python supports 'r' for reading (default, fails if file missing), 'w' for writing (overwrites or creates), 'a' for appending (adds to end), 'r+' for read-write (must exist), 'w+' for read-write (overwrites), 'a+' for append-read. Choose based on needs to avoid errors. Buffering affects performance; text mode uses 't', binary 'b'. CBSE emphasises understanding implications for safe operations.
How do you read specific lines from a file?
Use a loop with readline() to read line-by-line, or readlines() for a list then index. For line n, loop n-1 times discarding, then read. Example: for i, line in enumerate(file): if i == target: print(line). Handle end-of-file with try-except. This meets key question on constructing scripts.
Why is closing files important?
Closing flushes buffers to disk, frees OS handles, prevents corruption. Without it, data may not save, files stay locked. Use file.close() or context manager: with open('file.txt') as f: ... auto-closes. Best practice for reliable programmes, as per CBSE standards.
How does active learning help in file handling?
Active learning engages students by creating and manipulating actual files, observing mode effects firsthand, and debugging issues like permission errors. Pairs discuss outputs, reinforcing concepts. This builds problem-solving over passive reading, aligns with CBSE's computational thinking, and prepares for real applications like data processing.