Computer Science

Text File Handling in Python Class 12 CBSE (083): Complete Notes with File Modes, Read, Write, Seek & Tell

Class 12 · Computer Science

Text File Handling in Python (CBSE Class 12 Computer Science - 083)

A file is a collection of related information stored permanently on a storage device such as a hard disk or SSD. Python provides built-in functions to create, read, write, append, and manipulate files. File handling is one of the most important topics in CBSE Class 12 Computer Science as it enables programs to store data permanently.

Learning Objectives

  • Understand file handling in Python.
  • Learn relative and absolute file paths.
  • Open and close text files.
  • Understand different file opening modes.
  • Read and write data in text files.
  • Use the with statement.
  • Understand seek() and tell().
  • Manipulate data stored in text files.

What is a Text File?

A text file stores information in the form of readable characters such as letters, digits, and symbols. Text files usually have extensions like .txt, .csv, or .log.

Example: student.txt, marks.txt, notes.txt

Why Do We Use Files?

  • Store data permanently.
  • Retrieve data whenever required.
  • Handle large amounts of information.
  • Share information between programs.
  • Avoid losing data when the program terminates.

File Paths

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

1. Absolute Path

An absolute path gives the complete location of a file starting from the root directory.

Example (Windows)


C:\Users\Sam\Documents\Python\student.txt

Example (Linux)


/home/student/python/student.txt

2. Relative Path

A relative path specifies the location of a file relative to the current working directory.

Example


student.txt

data/student.txt

files/marks.txt
Exam Tip: CBSE frequently asks the difference between relative and absolute paths.

Opening a Text File

Python uses the open() function to open a file.

Syntax


file_object = open("filename","mode")

Example


file = open("student.txt","r")

File Opening Modes

Mode Description File Must Exist?
r Read only Yes
r+ Read and Write Yes
w Write only (creates new file or overwrites existing file) No
w+ Read and Write (overwrites existing file) No
a Append only No
a+ Read and Append No

Closing a File

After performing file operations, the file should be closed to free system resources.

Syntax


file.close()

Example


file = open("student.txt","r")

print(file.read())

file.close()

Opening a File Using the with Statement

The with statement automatically closes the file after the block of code finishes execution.

Syntax


with open("student.txt","r") as file:
    statements

Example


with open("student.txt","r") as file:
    print(file.read())
Best Practice: Always prefer using the with statement because it automatically closes the file.

Writing Data Using write()

The write() method writes a single string into a file.

Syntax


file.write(data)

Example


file = open("student.txt","w")

file.write("Welcome to Python")

file.close()

Writing Multiple Lines Using writelines()

The writelines() method writes multiple strings from a list into a file.

Example


file = open("student.txt","w")

lines = ["Python\n",
         "Java\n",
         "C++\n"]

file.writelines(lines)

file.close()

Appending Data Using write()

To add new data without deleting existing data, open the file in append mode.

Example


file = open("student.txt","a")

file.write("\nArtificial Intelligence")

file.close()

Reading Data Using read()

The read() method reads the complete contents of the file.

Example


file = open("student.txt","r")

print(file.read())

file.close()

Reading Data Using readline()

The readline() method reads only one line at a time.

Example


file = open("student.txt","r")

print(file.readline())
print(file.readline())

file.close()

Reading Data Using readlines()

The readlines() method reads all lines and returns them as a list.

Example


file = open("student.txt","r")

data = file.readlines()

print(data)

file.close()

Output


['Python\n',
 'Java\n',
 'C++\n']

The tell() Method

The tell() method returns the current position of the file pointer.

Example


file = open("student.txt","r")

print(file.tell())

file.read(5)

print(file.tell())

file.close()

Possible Output


0
5

The seek() Method

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

Syntax


file.seek(position)

Example


file = open("student.txt","r")

file.seek(10)

print(file.read())

file.close()

Using seek() and tell() Together


file = open("student.txt","r")

print(file.tell())

file.read(8)

print(file.tell())

file.seek(0)

print(file.tell())

file.close()

Manipulation of Data in a Text File

Text files do not support direct modification of data. To update or delete information, follow these steps:

  1. Open the original file in read mode.
  2. Read its contents.
  3. Modify the required data in memory.
  4. Write the updated data back to the file.

Example: Replace a Word


with open("student.txt","r") as file:
    data = file.read()

data = data.replace("Python","Java")

with open("student.txt","w") as file:
    file.write(data)

Comparison of Reading Methods

Method Purpose Return Type
read() Reads the complete file or specified number of characters. String
readline() Reads one line at a time. String
readlines() Reads all lines. List

Common Programming Errors

  • Opening a non-existing file in r mode.
  • Forgetting to close a file.
  • Using w mode accidentally, which deletes existing data.
  • Reading from a file opened in write mode.
  • Forgetting newline characters (\n) while writing multiple lines.
  • Using seek() with an invalid position.

Exam Tips

  • Memorize all six text file modes: r, r+, w, w+, a, a+.
  • Know the difference between read(), readline(), and readlines().
  • Understand the purpose of seek() and tell().
  • Remember that w mode overwrites existing data.
  • Prefer the with statement for safe file handling.
  • Practice simple programs involving reading, writing, and appending data.

Frequently Asked Questions (FAQs)

1. What is a text file?

A text file stores data in the form of readable characters.

2. Which function is used to open a file?

The open() function is used to open a file.

3. What is the difference between write() and writelines()?

write() writes a single string, whereas writelines() writes multiple strings (usually from a list).

4. What is the purpose of seek()?

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

5. What does tell() return?

The tell() method returns the current position of the file pointer.


Summary

  • Text files provide permanent storage for data.
  • Python uses the open() function to access files.
  • File paths can be absolute or relative.
  • Common file modes include r, r+, w, w+, a, and a+.
  • The with statement automatically closes files.
  • write() and writelines() are used to write data.
  • read(), readline(), and readlines() are used to read data.
  • seek() changes the file pointer position, while tell() returns its current position.
  • Text file data can be manipulated by reading, modifying, and rewriting the file contents.