OOP & Advanced Python

File Handling

01 · What is File Handling? File · File Handling · 1 of 11

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.

02 · Why Files are Needed File · File Handling · 2 of 11

Why Do We Need Files?

Normally when we create a variable:

Python
student_name = "Rahul"
marks = 85
salary = 50000
The data stays in memory only while the program is running.
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.txt
  • students.csv
  • students.json
  • students.xlsx
03 · Basic Workflow File · File Handling · 3 of 11

Basic File Handling Workflow

Open → Read / Write → Process → Close

Python syntax:

Python
file = open("filename.txt", "mode")
# perform operation
file.close()
04 · Creating a File File · File Handling · 4 of 11

Creating Your First File

Python
file = open("/content/students.txt", "w")
file.write("Welcome to KSR datavizon")
file.close()
This creates a new file named students.txt and writes text into it.
Always close the file after you finish working with it.
Python
# Check whether the file exists
!ls
Output
sample_data  students.txt
The file students.txt is now present in the working directory.
Python
# Display its contents
!cat students.txt
Output
Welcome to KSR datavizon
05 · File Modes File · File Handling · 5 of 11

Important File Modes

The mode tells Python what you want to do with the file.

ModeMeaning
"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.
06 · Reading a File File · File Handling · 6 of 11

Reading a File

Python
file = open("students.txt", "r")
content = file.read()
print(content)
file.close()
Output
Welcome to KSR datavizon
read() reads the entire content of the file as a single string.
Python
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.
07 · Writing & Appending File · File Handling · 7 of 11

Writing and Appending

Python
# 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.
08 · with Statement File · File Handling · 8 of 11

The with Statement (Recommended Way)

Using with automatically closes the file, even if an error occurs.

Python
with open("students.txt", "r") as file:
    content = file.read()
    print(content)
# file is automatically closed here
This is the preferred and safer way to work with files in Python.
09 · Pathlib File · File Handling · 9 of 11

Working with Paths using pathlib

pathlib is a modern and clean way to handle file paths.

Python
from pathlib import Path

file_path = Path("students.txt")
print(file_path.exists())
Output
True
Python
file_path.write_text("Welcome to Python")
print(file_path.read_text())
Output
Welcome to Python
Path objects make it easy to check if a file exists, read text, and write text.
10 · CSV Files File · File Handling · 10 of 11

CSV File Handling

CSV stands for Comma Separated Values.

Python
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)
Creates a CSV file and writes multiple rows at once using writerows().
Python
with open("students.csv", "r", encoding="utf-8") as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)
Output
['Name', 'Course', 'Fees']
['Rahul', 'Python', '30000']
['Priya', 'AI', '50000']
['Arjun', 'SQL', '20000']
Each row is returned as a list of strings.
11 · Summary File · File Handling · 11 of 11

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 with statement
  • Use pathlib for modern path handling
  • Use the csv module for CSV files
Home File Handling

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 →