CBSE Class 12 CS (083) - File Handling: Text Files

File Handling - Text Files

File handling enables a program to store data permanently on a storage device. This chapter covers reading from and writing to text files using Python, including file modes, the with statement, and various file methods as per the CBSE Class 12 Computer Science syllabus.

1. Introduction to File Handling

A file is a named location on a storage device where data is stored permanently. File handling refers to the process of performing operations on files such as creating, opening, reading, writing, and closing them.

Why file handling?

  • Data persists even after the program terminates.
  • Large amounts of data can be processed efficiently.
  • Data can be shared between different programs.
  • Enables data analysis and reporting.

Python provides built-in functions and methods for file handling through the open() function which returns a file object.

2. File Path

A file path specifies the location of a file on the storage device.

Path TypeDescriptionExample
Absolute PathComplete path from the root directoryC://Users/student/data.txt
Relative PathPath relative to the current directorydata.txt or ./data.txt

In Python, use forward slashes (/) or double backslashes (\\) in paths to avoid escape character issues.

3. Opening a File

The open() function is used to open a file. It returns a file object.

file_object = open(file_name, mode)

Parameters:

  • file_name: Name or path of the file to be opened.
  • mode: Specifies the purpose of opening (read, write, append, etc.).
f = open("sample.txt", "r")  # Open for reading

4. File Modes

ModeDescriptionFile PointerFile Does Not Exist
"r"Read (default)BeginningError
"w"WriteBeginningCreates new file
"a"AppendEndCreates new file
"x"Exclusive creationBeginningCreates new file
"r+"Read and writeBeginningError
"w+"Write and readBeginningCreates new file
"a+"Append and readEndCreates new file

For text files, the default mode is "r". Append "t" to explicitly specify text mode (e.g., "rt").

5. Closing a File

After completing file operations, the file should be closed using the close() method.

f = open("sample.txt", "r")
# Perform file operations
f.close()

Why close a file?

  • Frees system resources.
  • Ensures data is written completely.
  • Prevents accidental modifications.
  • Limits file access to other programs.

6. Writing to a Text File

The write() method writes a string to the file. The writelines() method writes a list of strings.

f = open("notes.txt", "w")
f.write("Python is a powerful programming language.\n")
f.write("It is used for web development, data science, and AI.\n")
f.close()

Important: The "w" mode overwrites the entire file. If the file contains existing data, it will be erased.

7. Reading from a Text File

The read() method reads the entire content of the file as a single string.

f = open("notes.txt", "r")
content = f.read()
print(content)
f.close()

You can specify the number of characters to read:

f = open("notes.txt", "r")
first_20 = f.read(20) # Read first 20 characters
print(first_20)
f.close()

8. The readline() Method

The readline() method reads one line at a time from the file. Each call returns the next line including the newline character.

f = open("notes.txt", "r")
line1 = f.readline()
line2 = f.readline()
print("Line 1:", line1)
print("Line 2:", line2)
f.close()

When the end of file is reached, readline() returns an empty string "".

9. The readlines() Method

The readlines() method reads all lines of the file and returns them as a list of strings.

f = open("notes.txt", "r")
lines = f.readlines()
for line in lines:
print(line.strip()) # strip() removes newline
f.close()

10. Appending to a File

The "a" (append) mode adds new content to the end of the file without erasing existing data.

f = open("notes.txt", "a")
f.write("This line is appended at the end.\n")
f.close()

If the file does not exist, the "a" mode creates a new file.

11. The with Statement

The with statement ensures that the file is properly closed after operations, even if an exception occurs. This is also called a context manager.

with open("notes.txt", "r") as f:
content = f.read()
print(content)
# File is automatically closed here

Advantages of using with:

  • Automatic file closing.
  • Cleaner and more readable code.
  • Safer exception handling.
  • No need to explicitly call close().

12. The tell() and seek() Methods

tell() returns the current position of the file pointer (in bytes from the beginning).

seek() moves the file pointer to a specified position.

with open("notes.txt", "r") as f:
print(f.tell()) # Output: 0 (beginning)
f.read(10)
print(f.tell()) # Output: 10
f.seek(0) # Move to beginning
print(f.tell()) # Output: 0

seek(offset, whence) syntax:

  • whence = 0: From beginning of file (default).
  • whence = 1: From current position.
  • whence = 2: From end of file.

13. Iterating Through a File

The file object is an iterator. You can loop through it directly to read line by line efficiently.

with open("notes.txt", "r") as f:
for line in f:
print(line.strip())

This approach is memory-efficient for large files because it reads one line at a time instead of loading the entire file.

14. write() vs writelines()

MethodParameterDescription
write()A single stringWrites the string to the file
writelines()A list/sequence of stringsWrites each item to the file (without adding newlines)
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("data.txt", "w") as f:
f.writelines(lines)

Note: writelines() does not add newline characters. You must include them in the strings.

15. Checking if a File Exists

Use the os.path.exists() or pathlib module to check if a file exists before opening it.

import os
if os.path.exists("notes.txt"):
with open("notes.txt", "r") as f:
print(f.read())
else:
print("File does not exist.")

16. Standard Streams

Python provides three standard file objects:

StreamFile ObjectPurpose
stdinsys.stdinStandard input (keyboard)
stdoutsys.stdoutStandard output (screen)
stderrsys.stderrStandard error (error messages)
import sys
sys.stdout.write("Hello using stdout\n")

17. Best Practices

  • Always use the with statement to handle files.
  • Specify the correct file mode to avoid accidental data loss.
  • Handle exceptions using try-except blocks for robust code.
  • Close files explicitly if not using with.
  • Use absolute paths sparingly; prefer relative paths.
  • Check if a file exists before reading.
  • Use strip() when reading lines to remove unwanted whitespace.
  • Be careful with "w" mode as it overwrites existing data.

18. Revision Questions and Answers

Very Short Answer Questions

1. Which function is used to open a file in Python?
The open() function.

2. What is the default file mode in Python?
The default mode is "r" (read text).

3. Which statement ensures automatic closing of a file?
The with statement.

4. What does the tell() method return?
The current position of the file pointer in bytes.

5. What happens if you open a non-existent file in "w" mode?
A new empty file is created.

Short Answer Questions

1. Differentiate between read() and readline().
read() reads the entire file content as a single string or specified number of characters. readline() reads one line at a time including the newline character. read() is suitable for small files, while readline() is memory-efficient for large files.

2. Explain the difference between "w" and "a" modes.
The "w" mode opens a file for writing and overwrites the existing content. The file pointer is placed at the beginning. The "a" mode opens a file for appending; new data is added at the end and existing content is preserved.

3. What is a context manager and how does it help in file handling?
A context manager, used with the with statement, automatically manages resources. In file handling, it ensures the file is properly closed after operations, even if an exception occurs. This eliminates the need for explicit close() calls and prevents resource leaks.

Long Answer Questions

1. Write a Python program to count the number of lines, words, and characters in a text file.

def count_file_stats(filename):
lines = words = chars = 0
with open(filename, "r") as f:
for line in f:
lines += 1
words += len(line.split())
chars += len(line)
return lines, words, chars

l, w, c = count_file_stats("sample.txt")
print(f"Lines: {l}, Words: {w}, Characters: {c}")

2. Explain seek() and tell() with examples. How can you read a file in reverse order?
tell() returns the current byte position. seek(offset, whence) moves the pointer. To read a file in reverse, you can seek to the end, then read backwards using seek(-1, 2) and process characters in reverse, handling multi-byte characters carefully.