File Handling
What is File Handling?
Think of file handling like working with a physical notebook:
Create notebook → Open notebook → Read something → Write something → Add more information → Close notebook
Python does exactly the same thing with files.
Why Do We Need Files?
Normally when we create a variable:
student_name = "Rahul"
marks = 85
salary = 50000
Once the runtime is restarted, the data disappears.
If Google Colab restarts, salary is gone.
But if you save it inside a file (for example salary.txt), then you can open that file tomorrow, next week, or in another program.
Variable → Temporary storage
File → Permanent storage
Real World Example
Imagine KSR Datavizon has 500 students. You want to store:
- Student name
- Course
- Fees
- Attendance
- Marks
- Placement Status
It would not make sense to type this information manually every time the program starts. Instead, you store it in files such as:
students.txtstudents.csvstudents.jsonstudents.xlsx
Basic File Handling Workflow
Open → Read / Write → Process → Close
Python syntax:
file = open("filename.txt", "mode")
# perform operation
file.close()
Creating Your First File
file = open("/content/students.txt", "w")
file.write("Welcome to KSR datavizon")
file.close()
students.txt and writes text into it.Always close the file after you finish working with it.
# Check whether the file exists
!ls
sample_data students.txt
students.txt is now present in the working directory.# Display its contents
!cat students.txt
Welcome to KSR datavizon
Important File Modes
The mode tells Python what you want to do with the file.
| Mode | Meaning |
|---|---|
"r" | Read (default). File must already exist. |
"w" | Write. Creates a new file or overwrites existing file. |
"a" | Append. Adds content at the end of the file. |
"x" | Create. Fails if the file already exists. |
"r+" | Read and write. |
"w+" | Write and read (overwrites). |
"a+" | Append and read. |
Reading a File
file = open("students.txt", "r")
content = file.read()
print(content)
file.close()
Welcome to KSR datavizon
read() reads the entire content of the file as a single string.
file = open("students.txt", "r")
print(file.readline()) # reads one line
print(file.readlines()) # reads all lines into a list
file.close()
readline() returns the next line.readlines() returns a list of all remaining lines.
Writing and Appending
# Write mode (overwrites the file)
file = open("students.txt", "w")
file.write("Rahul - Python\n")
file.write("Priya - AI\n")
file.close()
# Append mode (adds at the end)
file = open("students.txt", "a")
file.write("Arjun - SQL\n")
file.close()
"w" mode overwrites the existing content."a" mode adds new content at the end without deleting old content.
The with Statement (Recommended Way)
Using with automatically closes the file, even if an error occurs.
with open("students.txt", "r") as file:
content = file.read()
print(content)
# file is automatically closed here
Working with Paths using pathlib
pathlib is a modern and clean way to handle file paths.
from pathlib import Path
file_path = Path("students.txt")
print(file_path.exists())
True
file_path.write_text("Welcome to Python")
print(file_path.read_text())
Welcome to Python
Path objects make it easy to check if a file exists, read text, and write text.
CSV File Handling
CSV stands for Comma Separated Values.
import csv
students = [
["Name", "Course", "Fees"],
["Rahul", "Python", 30000],
["Priya", "AI", 50000],
["Arjun", "SQL", 20000]
]
with open("students.csv", "w", newline="", encoding="utf-8") as file:
writer = csv.writer(file)
writer.writerows(students)
writerows().with open("students.csv", "r", encoding="utf-8") as file:
reader = csv.reader(file)
for row in reader:
print(row)
['Name', 'Course', 'Fees'] ['Rahul', 'Python', '30000'] ['Priya', 'AI', '50000'] ['Arjun', 'SQL', '20000']
Summary
- Variables store data temporarily (in memory)
- Files store data permanently
- Basic workflow: Open → Read/Write → Close
- Important modes:
r,w,a - Always prefer the
withstatement - Use
pathlibfor modern path handling - Use the
csvmodule for CSV files
File Handling in Python
Learn how to create, read, write and manage files permanently.
Select any topic from the left sidebar to begin.
Start Learning →
