🧠 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:
🔍 Common File Modes:
Mode | Description |
---|---|
'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
🔹 If the file doesn’t exist, Python creates it.
🔹 If it exists, content is overwritten in 'w'
mode.
📖 Reading from a Text File
Other Reading Methods:
Method | Description |
---|---|
read(n) | Reads n characters |
readline() | Reads one line at a time |
readlines() | Reads all lines into a list |
➕ Appending to a Text File
✔️ 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.
⚠️ Best Practice: Use with
Statement
🛡️ 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
🔹 Program 2: Search for a word in a file
❓ Practice Questions:
📘 1 Mark – Objective:
-
What does the
open()
function return? - Name the file mode used to append content.
- Which method reads one line at a time?
- What will
readlines()
return?
✍️ 2 Marks – Short Answer:
-
Differentiate between
write()
andwritelines()
with examples. - What happens if you try to open a non-existing file in read mode?
💻 3 Marks – Programming:
- Write a program to display only the first 3 lines of a file.
- 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.