Python File Handling Tutorial | Read, Write, Append & Manage Files
Data is one of the most valuable assets in any software application. Whether it’s user information, transaction records, reports, logs, or configuration settings, applications need a reliable way to store and retrieve information. This is where File Handling becomes essential.
Python provides powerful file handling capabilities that allow developers to create, read, write, append, and manage files efficiently. File operations are widely used in web applications, automation, data analytics, artificial intelligence, banking software, hospital management systems, and enterprise applications.
In this lesson, you’ll learn how to work with text files, understand different file modes, safely manage files using the with statement, handle CSV files, and implement file operations in real-world projects.
By the end of this lesson, you’ll be able to build applications that store and retrieve data efficiently using Python file handling techniques.
Learning Objectives
After completing this lesson, you will be able to:
- Understand the importance of file handling.
- Create and open files.
- Read data from files.
- Write and append data to files.
- Work with different file modes.
- Use the
withstatement. - Handle CSV files.
- Delete files safely.
- Build applications using persistent file storage.
Topics Covered
- Introduction to File Handling
- Opening Files
- File Modes
- Reading Files
- Writing Files
- Appending Data
- The
withStatement - Working with CSV Files
- File Deletion
- Best Practices
Detailed Lesson Content
Introduction to File Handling
Imagine you’re building a Student Management System.
Every day, new students register for courses. Their information needs to be saved even after the program closes.
If you store data only in variables:
student = "Rahul"
the data disappears when the program ends.
To save information permanently, developers use files.
A file allows programs to:
- Store user information
- Save reports
- Maintain logs
- Export invoices
- Save AI model outputs
- Store application settings
File handling enables applications to work with persistent data.
What is a File?
A file is a collection of data stored on a storage device.
Examples:
- students.txt
- marks.csv
- report.pdf
- image.jpg
- data.json
Python can work with many file formats.
In this lesson, we’ll focus on text files.
Opening a File
Python uses the open() function.
Syntax
file = open("filename","mode")
Example
file = open("students.txt","r")
The first argument is the file name.
The second argument specifies the file mode.
File Modes
| Mode | Description |
|---|---|
| r | Read File |
| w | Write File |
| a | Append Data |
| x | Create New File |
| r+ | Read and Write |
| w+ | Write and Read |
| a+ | Append and Read |
| b | Binary Mode |
| t | Text Mode (Default) |
Reading a File
Suppose the file contains:
Rahul
Amit
Priya
Program:
file = open("students.txt","r")
print(file.read())
file.close()
Output
Rahul
Amit
Priya
Reading One Line
file = open("students.txt","r")
print(file.readline())
file.close()
Output
Rahul
Reading All Lines
file = open("students.txt","r")
print(file.readlines())
file.close()
Output
['Rahul', 'Amit', 'Priya']
Writing to a File
Write mode creates a new file or overwrites an existing one.
file = open("students.txt","w")
file.write("Rahul Sharma")
file.close()
After execution:
Rahul Sharma
Important: w mode erases existing content before writing new data.
Appending Data
Append mode adds new data without deleting existing content.
file = open("students.txt","a")
file.write("\nAmit Verma")
file.close()
Output
Rahul Sharma
Amit Verma
Append mode is commonly used for:
- Attendance Systems
- Log Files
- Reports
- Transaction History
The with Statement
Professional developers prefer using the with statement because it automatically closes the file after use.
Example
with open("students.txt","r") as file:
print(file.read())
No need to call:
file.close()
The file closes automatically.
This reduces the risk of memory leaks and resource locking.
Creating a New File
Use x mode.
file = open("report.txt","x")
file.close()
If the file already exists, Python raises a FileExistsError.
Working with CSV Files
CSV (Comma-Separated Values) files are widely used for storing structured data.
Example
Name,Age,Course
Rahul,21,Python
Amit,22,React
Python provides the csv module.
Example
import csv
with open("students.csv","r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
CSV files are commonly used in:
- Excel Reports
- Data Analytics
- Business Applications
- Machine Learning
Checking if a File Exists
Using the os module:
import os
if os.path.exists("students.txt"):
print("File Exists")
else:
print("File Not Found")
Deleting a File
import os
os.remove("students.txt")
Always check whether the file exists before deleting it.
Real-World Example 1: Student Registration
name = input("Enter Student Name: ")
with open("students.txt","a") as file:
file.write(name + "\n")
print("Student Saved Successfully")
Real-World Example 2: Feedback System
feedback = input("Enter Feedback: ")
with open("feedback.txt","a") as file:
file.write(feedback + "\n")
print("Thank You for Your Feedback")
Real-World Example 3: Attendance Management
students = ["Rahul","Amit","Priya"]
with open("attendance.txt","w") as file:
for student in students:
file.write(student+"\n")
Real-World Example 4: Reading Student Records
with open("students.txt","r") as file:
for line in file:
print(line.strip())
Output
Rahul
Amit
Priya
Common Mistakes
Forgetting to Close a File
Incorrect
file = open("students.txt","r")
print(file.read())
Correct
file.close()
Or use
with open(...)
Using Wrong File Mode
Trying to read a non-existent file using "r" causes a FileNotFoundError.
Use "w" or "a" if you intend to create the file.
Overwriting Important Data
Using "w" mode removes existing content.
If you want to keep previous data, use "a" mode.
Best Practices
- Prefer the
withstatement for automatic file closing. - Choose the correct file mode (
r,w,a,x). - Handle file-related exceptions using
try...except. - Validate file existence before deleting.
- Use meaningful file names.
- Store sensitive information securely.
- Close files after use if not using
with.
Key Takeaways
- Files store data permanently.
- Use
open()to work with files. rreads files.wwrites and overwrites files.aappends data.xcreates a new file.withautomatically closes files.- CSV files are commonly used for structured data.
- Always use proper file handling techniques to avoid data loss.



