Python File Handling – Read and Write Files
Published: 31 Oct, 2026 | Author: CCI Admin | Category: Python / Programming
Python File Handling allows us to store information in files and access it whenever required. Instead of keeping data only in program memory, we can save it in text files and use it later. In this blog, let us learn how to create, read, write, and append files using simple Python examples.
1. What Is File Handling in Python?
File handling is the process of creating, opening, reading, writing, and managing files using a program.
Python provides the built-in open() function to work with files.
Common file handling operations include:
- Creating a file
- Writing data into a file
- Reading data from a file
- Adding new data to an existing file
2. The open() Function
The open() function opens a file and returns a file object.
open("filename.txt", "mode")
The filename specifies the file to open. The mode specifies what operation we want to perform.
3. Common File Modes
| Mode | Meaning |
|---|---|
r |
Read an existing file |
w |
Write data; creates a file or replaces its existing content |
a |
Append data at the end of a file |
x |
Create a new file; fails if it already exists |
b |
Work with binary data |
4. Writing Data to a File
We can use the w mode to write text into a file.
If the file does not exist, Python creates it. If it already exists, its previous content is replaced.
with open("student.txt", "w", encoding="utf-8") as file:
file.write("Welcome to CCI Computer Education!")
file.write("\nLearn Python Programming.")
print("Data written successfully.")
Output:
Data written successfully.
The file student.txt will contain:
Welcome to CCI Computer Education!
Learn Python Programming.
5. Reading Data from a File
Use the r mode to read the contents of an existing file.
The read() method reads the file content as a string.
with open("student.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
Output:
Welcome to CCI Computer Education!
Learn Python Programming.
6. Appending Data to a File
The a mode adds new content at the end of a file without removing the existing content.
with open("student.txt", "a", encoding="utf-8") as file:
file.write("\nPractice Python every day!")
print("New content added.")
After appending, the file contains:
Welcome to CCI Computer Education!
Learn Python Programming.
Practice Python every day!
7. Reading a File Line by Line
When a file contains multiple lines, we can use a for loop to read each line separately.
with open("student.txt", "r", encoding="utf-8") as file:
for line in file:
print(line.strip())
The strip() method removes extra whitespace, including the newline character at the end of a line.
8. Practical Example – Save Student Details
Let us create a simple program that accepts a student's name and course, then saves the details in a file.
name = input("Enter student name: ")
course = input("Enter course name: ")
with open("student_details.txt", "w", encoding="utf-8") as file:
file.write(f"Student Name: {name}\n")
file.write(f"Course: {course}\n")
print("Student details saved successfully.")
Sample Input:
Enter student name: Arun
Enter course name: Python
File Content:
Student Name: Arun
Course: Python
9. Why Use the with Statement?
The with statement automatically closes the file after the operation is completed.
This helps manage files safely, even if an error occurs inside the block.
with open("student.txt", "r", encoding="utf-8") as file:
content = file.read()
print(content)
Using with is generally recommended instead of manually opening and closing files.
10. Common File Handling Errors
- FileNotFoundError: Trying to read a file that does not exist.
- Using the wrong mode: Opening a file in write mode may replace its old content.
- Incorrect file path: The file may be located in a different folder.
- Forgetting to close a file: Use the
withstatement to close it automatically.
11. Frequently Asked Questions (FAQ)
What is file handling in Python?
File handling is the process of creating, reading, writing, and managing files using Python.
Which function is used to open a file?
The built-in open() function is used to open a file.
What is the difference between w and a modes?
The w mode replaces existing content, while the a mode adds new content at the end.
Why is the with statement useful?
It automatically closes the file after the operation is completed.
Can Python read and write text files?
Yes. Python can read and write text files using modes such as r, w, and a.
12. Practice Tasks for Students
- Create a file named
myinfo.txtand write your name and age. - Read the contents of the file and display them.
- Append your favourite programming language to the file.
- Create a program to save five student names in a file.
Conclusion
Python File Handling is an important programming concept for storing and managing information.
By learning the open() function, file modes, read(), write(),
and the with statement, beginners can create useful programs that work with files.
At CCI Computer Education, students can strengthen their Python skills through simple examples, practical exercises, and project-based learning.
Related CCI Blogs
- Python Variables and Data Types
- Python Conditional Statements – if, elif and else
- Python Lists – Store and Manage Multiple Values
Contact CCI Computer Education – Pudukkottai
Want to learn Python programming with practical examples? Join CCI Computer Education and improve your programming skills. 👆Click Here
Call: 98427 97945
Website:
ccipudukkottai.com
WhatsApp Channel:
Follow CCI on WhatsApp
CCI Computer Education – Learn Today, Build Tomorrow.