Tuesday, October 6, 2026

๐Ÿ“– File Handling in Python – Save, Read and Manage Your Data

 

Learn • Experiment • Solve • Build

“A program that forgets everything when it closes isn't very useful. File handling teaches Python how to remember!”


๐ŸŒŸ Welcome to File Handling!

Imagine you create a Python program that stores student marks.

You run the program:

Raman - 92
Aman  - 85
Priya - 96

Everything works perfectly.

But then you close Python.

The next time you run the program...

Everything is gone! ๐Ÿ˜ฑ

Why?

Because the data was stored only in the computer's memory.

To permanently store information, we can use files.

Python Program
      ↓
   Data
      ↓
   File
      ↓
Saved permanently

This is called File Handling.


1. What is File Handling?

File handling means using Python to:

  • Create files

  • Open files

  • Read files

  • Write files

  • Add new information

  • Modify stored information

  • Work with structured data

  • Handle file-related errors

For example, Python can work with:

students.txt
marks.csv
students.json

2. Why Do We Need Files?

Consider a school management program.

It might need to store:

Student Name
Roll Number
Class
Marks
Address
Phone Number

If we store this information only in variables:

name = "Raman"
marks = 92

the information exists only while the program is running.

When the program stops, the variables disappear.

But if we save the information in a file:

students.txt

we can retrieve it later.

๐Ÿง  Python Pebble

Variables remember data temporarily. Files allow us to store data for future use.


3. Opening a File

Python provides the open() function.

Basic syntax:

file = open("filename.txt", "mode")

For example:

file = open("students.txt", "r")

Here:

students.txt → file name
r             → read mode

4. File Modes

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

ModeMeaning
rRead
wWrite
aAppend
xCreate a new file
r+Read and write
w+Write and read
a+Append and read

The most important modes for beginners are:

r → Read
w → Write
a → Append

5. Reading a File ๐Ÿ“–

Suppose students.txt contains:

Raman
Aman
Priya

We can read it using:

file = open("students.txt", "r")

data = file.read()

print(data)

file.close()

Output:

Raman
Aman
Priya

6. Why Do We Need close()?

When Python opens a file, it uses a system resource.

After finishing our work, we should close it.

file.close()

So the traditional pattern is:

file = open("students.txt", "r")

data = file.read()

print(data)

file.close()

But there is an even better way.


7. The Better Way – with open() ⭐

Python provides a safer and cleaner approach:

with open("students.txt", "r") as file:
    data = file.read()
    print(data)

Python automatically closes the file after the with block.

This means we don't need:

file.close()

๐Ÿง  Python Pebble

Prefer with open() when working with files.

It makes programs:

  • Safer

  • Cleaner

  • Easier to understand


8. Reading Line by Line

Instead of reading the entire file at once, we can process each line.

with open("students.txt", "r") as file:

    for line in file:
        print(line)

If the file contains:

Raman
Aman
Priya

Python processes:

Raman
Aman
Priya

one line at a time.

This is particularly useful for large files.


9. readline()

We can read one line at a time using readline().

with open("students.txt", "r") as file:

    print(file.readline())
    print(file.readline())

If the file contains:

Raman
Aman
Priya

Output:

Raman

Aman

10. readlines()

readlines() reads all lines and returns them as a list.

with open("students.txt", "r") as file:

    lines = file.readlines()

print(lines)

Output:

['Raman\n', 'Aman\n', 'Priya\n']

Notice the \n.

It represents a new line.


11. Removing the New Line

We can use strip().

with open("students.txt", "r") as file:

    for line in file:
        print(line.strip())

Output:

Raman
Aman
Priya

12. Writing to a File ✍️

Now let's create a file.

with open("students.txt", "w") as file:

    file.write("Raman\n")
    file.write("Aman\n")
    file.write("Priya\n")

The file will contain:

Raman
Aman
Priya

13. Important: Write Mode Can Replace Existing Data ⚠️

Suppose the file already contains:

Raman
Aman
Priya

Now we run:

with open("students.txt", "w") as file:
    file.write("Rahul\n")

The previous contents are replaced.

The file now contains:

Rahul

๐Ÿง  Remember

w means write/overwrite.

Be careful!


14. Appending Data ➕

What if we want to add information without deleting existing data?

Use a.

with open("students.txt", "a") as file:
    file.write("Neha\n")

If the file originally contains:

Raman
Aman
Priya

after appending:

Raman
Aman
Priya
Neha

๐Ÿง  Python Pebble

w → Replace
a → Add to the end


15. Writing Multiple Lines

We can use writelines().

students = ["Raman\n", "Aman\n", "Priya\n"]

with open("students.txt", "w") as file:
    file.writelines(students)

The file becomes:

Raman
Aman
Priya

16. Text Files

A normal .txt file is a text file.

Example:

student.txt

It can contain:

Name: Raman
Class: 9
Marks: 92

Python can read this information as text.

with open("student.txt", "r") as file:
    data = file.read()

print(data)

17. Creating a Simple Notes Program ๐Ÿ“

Let's build something useful.

note = input("Enter your note: ")

with open("notes.txt", "a") as file:
    file.write(note + "\n")

print("Note saved successfully!")

Example:

Enter your note: Complete Python homework
Note saved successfully!

Every time the program runs, a new note is added.


18. Reading Our Notes

with open("notes.txt", "r") as file:
    notes = file.read()

print("My Notes")
print("--------")
print(notes)

We have now created a tiny digital notebook using Python!


19. Handling File Errors ๐Ÿšจ

What happens if we try to open a file that doesn't exist?

with open("unknown.txt", "r") as file:
    print(file.read())

Python may generate:

FileNotFoundError

Instead of allowing the program to crash, we can handle the error.


20. Using try-except

try:

    with open("unknown.txt", "r") as file:
        print(file.read())

except FileNotFoundError:

    print("File does not exist.")

Output:

File does not exist.

Now our program is much more user-friendly.


21. Other Common File Exceptions

Some useful exceptions include:

ExceptionMeaning
FileNotFoundErrorFile doesn't exist
PermissionErrorFile cannot be accessed
IsADirectoryErrorA directory was used where a file was expected
UnicodeDecodeErrorFile encoding could not be decoded

For beginners, the most important one is:

FileNotFoundError

22. Reading and Writing Structured Data

So far, we stored simple text.

But real applications often store structured information.

For example:

Roll No: 101
Name: Raman
Marks: 92

Or:

101,Raman,92
102,Aman,85
103,Priya,96

Or:

{
    "roll": 101,
    "name": "Raman",
    "marks": 92
}

Python supports several ways to work with structured data.

Two important formats are:

  • CSV

  • JSON


23. CSV Files ๐Ÿ“Š

CSV stands for:

Comma-Separated Values

A CSV file might look like this:

Roll,Name,Marks
101,Raman,92
102,Aman,85
103,Priya,96

CSV is commonly used for:

  • Student records

  • Employee data

  • Sales data

  • Marks

  • Expenses

  • Reports


24. Writing a CSV File

Python has a built-in csv module.

import csv

students = [
    [101, "Raman", 92],
    [102, "Aman", 85],
    [103, "Priya", 96]
]

with open("students.csv", "w", newline="") as file:

    writer = csv.writer(file)

    writer.writerow(["Roll", "Name", "Marks"])
    writer.writerows(students)

This creates:

Roll,Name,Marks
101,Raman,92
102,Aman,85
103,Priya,96

25. Reading a CSV File

import csv

with open("students.csv", "r") as file:

    reader = csv.reader(file)

    for row in reader:
        print(row)

Output:

['Roll', 'Name', 'Marks']
['101', 'Raman', '92']
['102', 'Aman', '85']
['103', 'Priya', '96']

Notice that values read from CSV are generally strings.

If we need marks as numbers:

marks = int(row[2])

26. CSV Using Dictionaries

A very useful approach is DictReader.

import csv

with open("students.csv", "r") as file:

    reader = csv.DictReader(file)

    for row in reader:
        print(row["Name"], row["Marks"])

Output:

Raman 92
Aman 85
Priya 96

This is easier to understand because we can use column names.


27. JSON Files ๐Ÿค–

JSON stands for:

JavaScript Object Notation

Don't let the name worry you!

JSON is simply a popular format for storing structured data.

Example:

{
    "name": "Raman",
    "class": 9,
    "marks": 92
}

JSON is commonly used by:

  • Websites

  • Apps

  • APIs

  • Databases

  • AI applications

  • Data exchange systems


28. Writing JSON Using Python

Python provides the json module.

import json

student = {
    "roll": 101,
    "name": "Raman",
    "class": 9,
    "marks": 92
}

with open("student.json", "w") as file:
    json.dump(student, file, indent=4)

The file contains:

{
    "roll": 101,
    "name": "Raman",
    "class": 9,
    "marks": 92
}

29. Reading JSON

import json

with open("student.json", "r") as file:

    student = json.load(file)

print(student)

Output:

{'roll': 101, 'name': 'Raman', 'class': 9, 'marks': 92}

We can access individual values:

print(student["name"])
print(student["marks"])

Output:

Raman
92

30. JSON with Multiple Students

We can store a list of dictionaries.

import json

students = [
    {
        "roll": 101,
        "name": "Raman",
        "marks": 92
    },
    {
        "roll": 102,
        "name": "Aman",
        "marks": 85
    },
    {
        "roll": 103,
        "name": "Priya",
        "marks": 96
    }
]

with open("students.json", "w") as file:
    json.dump(students, file, indent=4)

Now we have a structured student database stored in a file!


31. Reading Structured JSON Data

import json

with open("students.json", "r") as file:
    students = json.load(file)

for student in students:
    print(
        student["roll"],
        student["name"],
        student["marks"]
    )

Output:

101 Raman 92
102 Aman 85
103 Priya 96

32. Updating JSON Data

Suppose Raman's marks change from 92 to 95.

We can:

  1. Read the file

  2. Modify the data

  3. Write it back

import json

with open("students.json", "r") as file:
    students = json.load(file)

for student in students:
    if student["roll"] == 101:
        student["marks"] = 95

with open("students.json", "w") as file:
    json.dump(students, file, indent=4)

This is the basic idea behind many real-world data-management programs.


33. Text vs CSV vs JSON

Which format should we use?

FormatBest For
TXTSimple text
CSVTables and spreadsheet-like data
JSONStructured/nested data

For example:

TXT

Raman
Aman
Priya

CSV

101,Raman,92
102,Aman,85

JSON

{
    "roll": 101,
    "name": "Raman",
    "marks": 92
}

34. File Handling + String Processing

Remember our previous Python Pebble about strings?

File handling and strings work very well together.

Suppose a file contains:

Python is easy
Python is powerful
Python is fun

We can count the number of times Python appears.

with open("message.txt", "r") as file:

    data = file.read()

count = data.lower().count("python")

print("Python appears", count, "times.")

Output:

Python appears 3 times.

Now we are combining:

Files + Strings + Conditions + Counting

That's how programming becomes powerful!


35. Mini Project – Student Record Management ๐ŸŽ“

Let's build something bigger.

Our application will store student information in a JSON file.

Each student will have:

Roll Number
Name
Class
Marks

We will create a menu:

===== STUDENT RECORD MANAGEMENT =====

1. Add Student
2. View Students
3. Search Student
4. Update Marks
5. Delete Student
6. Exit

36. Step 1 – Load Existing Records

import json

FILE_NAME = "students.json"

def load_students():

    try:
        with open(FILE_NAME, "r") as file:
            return json.load(file)

    except FileNotFoundError:
        return []

If the file doesn't exist, we return an empty list.


37. Step 2 – Save Records

def save_students(students):

    with open(FILE_NAME, "w") as file:
        json.dump(students, file, indent=4)

This function stores the current records.


38. Step 3 – Add a Student

def add_student(students):

    roll = input("Enter roll number: ")
    name = input("Enter student name: ")
    student_class = input("Enter class: ")
    marks = float(input("Enter marks: "))

    student = {
        "roll": roll,
        "name": name,
        "class": student_class,
        "marks": marks
    }

    students.append(student)

    save_students(students)

    print("Student added successfully!")

39. Step 4 – Display Students

def view_students(students):

    if not students:
        print("No student records found.")
        return

    for student in students:

        print(
            f"Roll: {student['roll']}, "
            f"Name: {student['name']}, "
            f"Class: {student['class']}, "
            f"Marks: {student['marks']}"
        )

40. Step 5 – Search Student

def search_student(students):

    roll = input("Enter roll number to search: ")

    for student in students:

        if student["roll"] == roll:

            print("\nStudent Found")
            print("Name:", student["name"])
            print("Class:", student["class"])
            print("Marks:", student["marks"])

            return

    print("Student not found.")

41. Step 6 – Update Marks

def update_marks(students):

    roll = input("Enter roll number: ")

    for student in students:

        if student["roll"] == roll:

            new_marks = float(
                input("Enter new marks: ")
            )

            student["marks"] = new_marks

            save_students(students)

            print("Marks updated successfully!")

            return

    print("Student not found.")

42. Step 7 – Delete a Student

def delete_student(students):

    roll = input("Enter roll number: ")

    for student in students:

        if student["roll"] == roll:

            students.remove(student)

            save_students(students)

            print("Student deleted successfully!")

            return

    print("Student not found.")

43. Step 8 – Create the Menu

Now let's bring everything together.

def main():

    students = load_students()

    while True:

        print("\n===== STUDENT RECORD MANAGEMENT =====")
        print("1. Add Student")
        print("2. View Students")
        print("3. Search Student")
        print("4. Update Marks")
        print("5. Delete Student")
        print("6. Exit")

        choice = input("Enter your choice: ")

        if choice == "1":
            add_student(students)

        elif choice == "2":
            view_students(students)

        elif choice == "3":
            search_student(students)

        elif choice == "4":
            update_marks(students)

        elif choice == "5":
            delete_student(students)

        elif choice == "6":
            print("Thank you!")
            break

        else:
            print("Invalid choice.")

Finally:

main()

44. Complete Student Record Program

import json

FILE_NAME = "students.json"


def load_students():

    try:
        with open(FILE_NAME, "r") as file:
            return json.load(file)

    except FileNotFoundError:
        return []


def save_students(students):

    with open(FILE_NAME, "w") as file:
        json.dump(students, file, indent=4)


def add_student(students):

    roll = input("Enter roll number: ")
    name = input("Enter student name: ")
    student_class = input("Enter class: ")
    marks = float(input("Enter marks: "))

    student = {
        "roll": roll,
        "name": name,
        "class": student_class,
        "marks": marks
    }

    students.append(student)

    save_students(students)

    print("Student added successfully!")


def view_students(students):

    if not students:
        print("No student records found.")
        return

    for student in students:

        print(
            f"Roll: {student['roll']}, "
            f"Name: {student['name']}, "
            f"Class: {student['class']}, "
            f"Marks: {student['marks']}"
        )


def search_student(students):

    roll = input("Enter roll number to search: ")

    for student in students:

        if student["roll"] == roll:

            print("\nStudent Found")
            print("Name:", student["name"])
            print("Class:", student["class"])
            print("Marks:", student["marks"])

            return

    print("Student not found.")


def update_marks(students):

    roll = input("Enter roll number: ")

    for student in students:

        if student["roll"] == roll:

            new_marks = float(input("Enter new marks: "))

            student["marks"] = new_marks

            save_students(students)

            print("Marks updated successfully!")

            return

    print("Student not found.")


def delete_student(students):

    roll = input("Enter roll number: ")

    for student in students:

        if student["roll"] == roll:

            students.remove(student)

            save_students(students)

            print("Student deleted successfully!")

            return

    print("Student not found.")


def main():

    students = load_students()

    while True:

        print("\n===== STUDENT RECORD MANAGEMENT =====")
        print("1. Add Student")
        print("2. View Students")
        print("3. Search Student")
        print("4. Update Marks")
        print("5. Delete Student")
        print("6. Exit")

        choice = input("Enter your choice: ")

        if choice == "1":
            add_student(students)

        elif choice == "2":
            view_students(students)

        elif choice == "3":
            search_student(students)

        elif choice == "4":
            update_marks(students)

        elif choice == "5":
            delete_student(students)

        elif choice == "6":
            print("Thank you!")
            break

        else:
            print("Invalid choice.")


main()

๐Ÿงช Sample Run

===== STUDENT RECORD MANAGEMENT =====

1. Add Student
2. View Students
3. Search Student
4. Update Marks
5. Delete Student
6. Exit

Enter your choice: 1

Enter roll number: 101
Enter student name: Raman
Enter class: 9
Enter marks: 92

Student added successfully!

Now the information is stored in:

students.json

Even if the program is closed, the record remains.

That is the real power of file handling!


๐Ÿง  Python Pebble Challenge 1 – Predict the Output

Suppose data.txt contains:

Python
Programming

What will this program display?

with open("data.txt", "r") as file:
    data = file.read()

print(len(data))

Don't run it immediately.

Count the characters yourself!


๐Ÿง  Python Pebble Challenge 2 – Find the Bug

What's wrong here?

file = open("students.txt", "r")

data = file.read()

print(data)

Hint

Think about resource management.

How could with open() improve this code?


๐Ÿง  Python Pebble Challenge 3 – Append Data

Write a program that:

  1. Asks the user for their name.

  2. Adds the name to names.txt.

  3. Does not delete previous names.


๐Ÿง  Python Pebble Challenge 4 – Count Words

Create a program that reads story.txt and displays:

Number of words: 125

Hint

Use:

split()

๐Ÿง  Python Pebble Challenge 5 – Find a Student

Create a program that reads students.json and searches for a student using their roll number.

Display:

Student Found
Name: Raman
Marks: 92

or:

Student not found.

๐Ÿ† Master Challenge – Improve the Student Management System

The basic project is only the beginning.

Try adding:

Level 1

  • Calculate average marks

  • Find highest marks

  • Find lowest marks

  • Count students

Level 2

  • Search by name

  • Search by class

  • Sort students by marks

  • Display students scoring above 90

Level 3

  • Calculate grades

  • Prevent duplicate roll numbers

  • Validate marks between 0 and 100

  • Handle invalid numeric input

  • Add date of birth

Level 4 ๐Ÿš€

Add:

  • Attendance

  • Subject-wise marks

  • Percentage

  • Grade

  • Rank

  • Export to CSV

  • Import from CSV

  • JSON backup

  • Student report generation

Now you've moved from a simple Python program to a small Student Management Application.


๐Ÿ“Œ File Handling Quick Revision

ConceptPython
Open fileopen()
Read entire fileread()
Read one linereadline()
Read all linesreadlines()
Writewrite()
Write multiple lineswritelines()
Automatically closewith open()
Read moder
Write modew
Append modea
Create new filex
CSVcsv module
JSONjson module
Handle missing fileFileNotFoundError

๐ŸŽฏ TXT vs CSV vs JSON – Remember This

Think of three different notebooks.

๐Ÿ“’ TXT

Good for simple notes.

Python is fun.
Python is powerful.

๐Ÿ“Š CSV

Good for tables.

Roll,Name,Marks
101,Raman,92
102,Aman,85

๐Ÿ—‚️ JSON

Good for structured information.

{
    "roll": 101,
    "name": "Raman",
    "marks": 92
}

๐Ÿชจ One Final Python Pebble

File handling connects many Python concepts together:

             FILE HANDLING
                  │
       ┌──────────┼──────────┐
       ↓          ↓          ↓
      TXT        CSV        JSON
       │          │          │
       └──────────┼──────────┘
                  ↓
             Python Data
                  ↓
        ┌─────────┼─────────┐
        ↓         ↓         ↓
      Read      Write     Update
        │         │         │
        └─────────┼─────────┘
                  ↓
             REAL PROJECTS
                  ↓
        Student Record System

The important thing to remember is:

A good program processes data. A useful program also knows how to save that data.

Once you understand file handling, your Python programs don't have to forget everything when they close.

You can now build programs that store, retrieve, search, update and manage real information.


๐Ÿš€ Your Next Mission

Build these projects in order:

  1. ๐Ÿ“ Digital Notes App

  2. ๐Ÿ“– Simple Diary

  3. ๐Ÿ“Š Marks Record using CSV

  4. ๐Ÿ—‚️ Contact Book using JSON

  5. ๐ŸŽ“ Student Record Management System

And then challenge yourself:

Can you build a complete Student Management System that stores all its data in JSON and also generates a CSV report?

That's your next Python Pebble!

No comments:

Post a Comment

๐Ÿ“– File Handling in Python – Save, Read and Manage Your Data

  Learn • Experiment • Solve • Build “A program that forgets everything when it closes isn't very useful. File handling teaches Python h...