12.4 Text File Handling in Python – A Complete Guide for Class XII CBSE

 


🧠 What is a Text File?

A text file is a file that contains characters and lines you can read using a text editor like Notepad. Python allows you to create, read, write, and append text files using simple functions.


🔧 File Handling Operations in Python

Python uses the built-in open() function to work with files.

✅ Basic Syntax:

python

file = open("filename.txt", "mode") # perform file operations file.close()

🔍 Common File Modes:

ModeDescription
'r'Read mode (default)
'w'Write mode (overwrites if file exists)
'a'Append mode
'r+'Read and write
'w+'Write and read (overwrites existing content)

✍️ Writing to a Text File

python

f = open("notes.txt", "w") f.write("Welcome to File Handling!\n") f.write("This is a text file.") f.close()

🔹 If the file doesn’t exist, Python creates it.
🔹 If it exists, content is overwritten in 'w' mode.


📖 Reading from a Text File

python

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

Other Reading Methods:

MethodDescription
read(n)Reads n characters
readline()Reads one line at a time
readlines()Reads all lines into a list

➕ Appending to a Text File

python

f = open("notes.txt", "a") f.write("\nThis line is appended.") f.close()

✔️ No content is overwritten; new data is added at the end.


🧭 File Pointer and seek() Method

The file pointer keeps track of the current position in the file.

python
f = open("notes.txt", "r") f.seek(5) # Moves pointer to the 6th character print(f.read()) # Reads from position 5 onwards f.close()

⚠️ Best Practice: Use with Statement

python
with open("notes.txt", "r") as f: content = f.read() print(content)

🛡️ Advantage: Automatically closes the file, even if an error occurs.


📌 Important Notes:

  • Always close the file after operations to free resources.

  • Use exception handling (try-except) to manage errors like "File Not Found".


💡 Example Programs:

🔹 Program 1: Count the number of lines in a file

python
f = open("notes.txt", "r") lines = f.readlines() print("Total lines:", len(lines)) f.close()

🔹 Program 2: Search for a word in a file

python
f = open("notes.txt", "r") word = "Python" found = False for line in f: if word in line: found = True break f.close() print("Word found!" if found else "Word not found.")

❓ Practice Questions:

📘 1 Mark – Objective:

  1. What does the open() function return?
  2. Name the file mode used to append content.
  3. Which method reads one line at a time?
  4. What will readlines() return?

✍️ 2 Marks – Short Answer:

  1. Differentiate between write() and writelines() with examples.
  2. What happens if you try to open a non-existing file in read mode?

💻 3 Marks – Programming:

  1. Write a program to display only the first 3 lines of a file.
  2. Write a program to copy contents from one file to another.

🧠 5 Marks – Case-Based:

Given a file named report.txt containing student names and marks (one per line). Write a program to:

  • Read the content line by line
  • Display only the names of students who scored above 80


🎯 Tips to Score Full Marks:

  • Remember to close or use with to avoid losing marks.
  • Use clear variable names and indentation in your code.
  • Practice past year questions for better confidence.


📝 Conclusion

Text file handling is one of the most scoring and practical topics in the CBSE Class XII syllabus. With just a few functions like open(), read(), and write(), you can perform powerful file operations that are often used in real-world applications.

Previous Post Next Post