(Grade X)File Handling

 



1. Why File Handling?

Normal variables and lists lose their data as soon as the program ends (this is called volatile memory). A file stores data permanently on the disk (non-volatile memory), so we can use it again later — even after the computer is switched off.

 

File Modes

Mode

Meaning

r

Read (default). File must exist.

w

Write. Creates new file / erases existing content.

a

Append. Adds data at the end without erasing.

 

2. Opening and Closing a File

file = open("data.txt", "w")   # open the file

file.close()                    # always close after use

 

Syntax:

variable = open("filename", "mode")

 

3. Programs

3.1 Writing to a file (Simple)

f = open("student.txt", "w")

f.write("Ram\n")

f.write("Shyam\n")

f.close()

 

3.2 Reading a whole file

f = open("student.txt", "r")

print(f.read())

f.close()

 

3.4 Appending data (adding without deleting old data)

f = open("student.txt", "a")

f.write("Hari\n")

f.close()

 

3.5 Copying a file

src = open("student.txt", "r")

dest = open("backup.txt", "w")

for line in src:

    dest.write(line)

src.close()

dest.close()

 

3.6 Deleting a file (using os module)

import os

if os.path.exists("backup.txt"):

    os.remove("backup.txt")

else:

    print("File not found")


Practice Questions

  1. Write a Python program to create a sequential data file employee.txt and store the records of 5 employees. Each record should contain Employee ID, Name, Department, and Address.
  2. Write a Python program to add a new employee record to the existing file employee.txt.
  3. Write a Python program to display all the records of employees from employee.txt.
  4. Write a Python program to display the employee record whose Employee ID is 3.
  5. Write a Python program to display the employee record whose Employee Address is Patan.
  6. Write a Python program to copy all the records of employees from employee.txt into a new file newemployee.txt.
  7. Write a Python program to delete the record of an employee whose Employee ID is 3 from employee.txt.

File Handling — CSV

What is a CSV File?

A simple, common format for storing tabular data as plain text.

CSV = Comma Separated Values. It stores tabular data (like a spreadsheet) in a plain text file. Each line is a row; values in a row are separated by commas.

Python's built-in csv module reads and writes these files easily. Import it before use:

import csv

This one line gives access to csv.writer(), csv.reader(), and related tools used throughout this lesson.

Writing to a CSV File (STORE)

import csv

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

    writer = csv.writer(f)

    writer.writerow(["Roll","Name","Class","Address","Gender"])

    writer.writerow([1, "Ram", 10, "Kathmandu", "Male"])

    writer.writerow([2, "Sita", 9, "Pokhara", "Female"])

    writer.writerow([3, "Hari", 10, "Chitwan", "Male"])

    writer.writerow([4, "Rita", 8, "Kathmandu", "Female"])

    writer.writerow([5, "Rohan", 10, "Lalitpur", "Male"])

Understanding the Code

Part

Meaning

with

Used to work with a file safely. It automatically closes the file when the work is finished.

open()

Opens or creates a file.

"students.csv"

The name of the file we want to open.

"w"

Write mode

newline=""

Prevents extra blank lines from appearing between CSV records.

as f

Gives the opened file a short name, f, so we can use f to refer to the file.

 

Writing Records Using a Loop

Take input from the user to store a fixed number of records (e.g., 10 students).

import csv

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

    writer = csv.writer(f)

    writer.writerow(["Roll", "Name", "Class", "Address", "Gender"])

    for i in range(10):

        print("\nEnter details of student", i + 1)

        roll = input("Enter Roll: ")

        name = input("Enter Name: ")

        class_no = input("Enter Class: ")

        address = input("Enter Address: ")

        gender = input("Enter Gender: ")

        data = [roll, name, class_no, address, gender]

        writer.writerow(data)

Writing Records Until User's Choice

Keep asking for records until the user chooses to stop.

import csv

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

    writer = csv.writer(f)

    writer.writerow(["Roll", "Name", "Class", "Address", "Gender"])

    while True:

        roll = input("Enter Roll: ")

        name = input("Enter Name: ")

        class_no = input("Enter Class: ")

        address = input("Enter Address: ")

        gender = input("Enter Gender: ")

        data = [roll, name, class_no, address, gender]

        writer.writerow(data)

        choice = input("Do you want to continue? (y/n): ")

        if choice.lower() != "y":

            break

Adding a New Record (ADD)

Use mode "a" (append) to add a record without erasing existing data.

import csv

with open("students.csv", "a", newline="") as f:

    writer = csv.writer(f)

    writer.writerow([6, "Gita", 9, "Bhaktapur", "Female"])

Displaying All Records

Read the file with csv.reader() and print every row.

import csv

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

    reader = csv.reader(f)

    next(reader)   # skip the header

    for row in reader:

        print(row)

Display Record of a Specific Roll Number

Find and display the student whose Roll number is 4.

import csv

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

    reader = csv.reader(f)

    next(reader)   # skip the header

    for row in reader:

        if row[0] == "4":

            print(row)

Display Students Whose Class Is More Than 8

Convert the class column to int() before comparing numbers.

import csv

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

    reader = csv.reader(f)

    next(reader)   # skip the header

    for row in reader:

        if int(row[2]) > 8:

            print(row)

Display Record by Address ("Chitwan")

Match the Address column exactly against the target string.

import csv

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

    reader = csv.reader(f)

    next(reader)    # skip header

    for row in reader:

        if row[3] == "Chitwan":

            print(row)

Display Students Whose Name Starts With "R"

Use the string method .startswith() on the Name column.

import csv

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

    reader = csv.reader(f)

    next(reader)    # skip header

    for row in reader:

        if row[1].startswith("R"):

            print(row)

Display Students by Address AND Class

Combine two conditions with "and" — Address is "Kathmandu" and Class is 10.

import csv

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

    reader = csv.reader(f)

    next(reader)    # skip header

    for row in reader:

        if row[3] == "Kathmandu" and int(row[2]) == 10:

            print(row)

Deleting a Record

CSV has no direct delete: read all rows, skip the unwanted one, then rewrite the file.

import csv

roll_to_delete = "2"

rows = []

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

    reader = csv.reader(f)

    for row in reader:

        if row[0] != roll_to_delete:

            rows.append(row)

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

    writer = csv.writer(f)

    writer.writerows(rows)

Copying a CSV File

Open the source for reading and the destination for writing at the same time.

import csv

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

    with open("students_copy.csv", "w", newline="") as dest:

        reader = csv.reader(src)

        writer = csv.writer(dest)

        for row in reader:

            writer.writerow(row)


 

Practice Exercises

1. Write a program to create a file patients.csv and store the header (Patient_ID, Name, Ward, Age, Disease, Gender) followed by records for 5 patients.

2. Write a program that takes input from the user and stores records of 10 patients into patients.csv.

3. Write a program that keeps asking for patient details and stores them into patients.csv until the user chooses to stop.

4. Write a program to add a new patient's record to the existing patients.csv file without deleting previous records.

5. Write a program to read patients.csv and display all the records.

6. Write a program to display the record of the patient whose Patient_ID is 421.

7. Write a program to display the records of all patients whose age is greater than 60.

8. Write a program to display the records of patients whose Ward is "ICU".

9. Write a program to display all patients whose disease starts with the letter "S".

10. Write a program to display patients whose Ward is "ICU" and Age is greater than 50.

11. Write a program to delete the record of the patient whose Patient_ID is 132 from patients.csv.

12. Write a program to copy all records from patients.csv into a new file patients_backup.csv.


File Handling — Panda

1. Create a Series

import pandas as pd

marks = pd.Series([45, 67, 78, 89, 56])

print(marks)

 

Output

0    45

1    67

2    78

3    89

4    56

dtype: int64

 

2. Create a DataFrame

import pandas as pd

data = {

    "Name": ["Ram", "Sita", "Hari"],

    "Marks": [78, 85, 67]

}

df = pd.DataFrame(data)

print(df)

 

Output

   Name  Marks

0   Ram     78

1  Sita     85

2  Hari     67


 import pandas as pd

data = {

    "Name": ["Ram", "Sita", "Hari"],

    "Marks": [78, 85, 67]

}

df = pd.DataFrame(data)

print(df.to_string(index=False))

 

Meaning

 

df

The DataFrame we created

 

.to_string()

Converts the DataFrame into a text format for displaying

 

index=False

Tells pandas not to display the index numbers

 

3. Display selected column

import pandas as pd

data = {

    "Name": ["Ram", "Sita", "Hari"],

    "Marks": [78, 85, 67]

}

df = pd.DataFrame(data)

print(df["Name"])

 

Output

0     Ram

1    Sita

2    Hari

Name: Name, dtype: str

4. Store in CSV file

import pandas as pd

 

# Store student details

data = {

    "Roll": [1, 2, 3],

    "Name": ["Ram", "Sita", "Hari"],

    "Class": [10, 10, 10],

    "Address": ["Kathmandu", "Lalitpur", "Bhaktapur"]

}

df = pd.DataFrame(data)

# Store data in CSV file

df.to_csv("students.csv", index=False)

Meaning

df → your DataFrame

.to_csv() → saves the DataFrame as a CSV file

"students.csv" → name of the CSV file

index=False → does not save Pandas' index numbers (0, 1, 2...) into the file.



5. Read a CSV file

import pandas as pd

df = pd.read_csv("students.csv")

print(df)

 

   Roll  Name  Class    Address

0     1   Ram     10  Kathmandu

1     2  Sita     10   Lalitpur

2     3  Hari     10  Bhaktapur

 

6. Display only selected columns

import pandas as pd

df = pd.read_csv("students.csv")

print(df["Name", "Address"])

   Name    Address

0   Ram  Kathmandu

1  Sita   Lalitpur

2  Hari  Bhaktapur

 

7. Display one particular column

import pandas as pd

df = pd.read_csv("students.csv")

print(df["Name"])

0     Ram

1    Sita

2    Hari

Name: Name, dtype: str

 

8. Display students whose marks are greater than 70

import pandas as pd

df = pd.read_csv("students.csv")

print(df[df["Marks"] > 70])

 

9. Marks greater than 60 AND class 10

import pandas as pd

df = pd.read_csv("students.csv")

print(df[(df["Marks"] > 60) & (df["Class"] == 10)])

 

10. Marks greater than 80 OR less than 40

import pandas as pd

df = pd.read_csv("students.csv")

print(df[(df["Marks"] > 80) | (df["Marks"] < 40)])

 

& → AND

| → OR