← Back to Python List

Question 3: CSV File Operations

Write a menu-driven program to add and display records in a CSV file (students.csv) which contains at least three student records with the following fields:

Solution

[Run Online]

# Question 3:
# Write a program to manage student records using CSV file.
# The program should allow user to add new student records
# (Name, Class, Roll No, Marks) and display all records.

import csv


# Function to add a new student record
def add_record():
    with open("students.csv", "a", newline="") as f:
        writer = csv.writer(f)
        name = input("Enter Name: ")
        clas = int(input("Enter Class: "))
        roll = int(input("Enter Roll No: "))
        marks = int(input("Enter Marks: "))
        writer.writerow([name, clas, roll, marks])
        print("Record added successfully!")


# Function to display all student records
def display_records():
    try:
        with open('students.csv', 'r') as f:
            reader = csv.reader(f)
            print("\n--- Raw CSV Output ---")
            # Printing the Header
            print("Name,Class,Roll,Marks") 
            print("-" * 25)
            
            for row in reader:
                # 'row' is a list like ['Rahul', '12', '1', '95']
                # ','.join(row) sticks them together with commas
                print(",".join(row)) 
    except FileNotFoundError:
        print("File not found! Add a record first.")

# Main Menu
while True:
    print("\n--- Student Management System ---")
    print("1. Add Student Record")
    print("2. Display All Records")
    print("3. Exit")
    choice = input("Enter your choice (1-3): ")
    if choice == "1":
        add_record()
    elif choice == "2":
        display_records()
    elif choice == "3":
        print("Exiting program. Goodbye!")
        break
    else:
        print("Invalid choice! Please try again.")

# Question 3:
# Write a program to manage student records using CSV file.
# The program should allow user to add 3 student records at once
# (Name, Class, Roll No, Marks) and display all records.

import csv


# Function to add 3 student records at once
def add_record():
    with open("students.csv", "a", newline="") as f:
        writer = csv.writer(f)
        for i in range(1, 4):
            print(f"\n--- Enter details for Student {i} ---")
            name = input("Enter Name: ")
            clas = int(input("Enter Class: "))
            roll = int(input("Enter Roll No: "))
            marks = int(input("Enter Marks: "))
            writer.writerow([name, clas, roll, marks])
            print(f"Record {i} added successfully!")
        print("\nAll 3 records have been added!")


# Function to display all student records
def display_records():
    try:
        with open('students.csv', 'r') as f:
            reader = csv.reader(f)
            print("\n--- Raw CSV Output ---")
            # Printing the Header
            print("Name,Class,Roll,Marks") 
            print("-" * 25)
            
            for row in reader:
                # 'row' is a list like ['Rahul', '12', '1', '95']
                # ','.join(row) sticks them together with commas
                print(",".join(row)) 
    except FileNotFoundError:
        print("File not found! Add a record first.")

# Main Menu
while True:
    print("\n--- Student Management System ---")
    print("1. Add Student Record")
    print("2. Display All Records")
    print("3. Exit")
    choice = input("Enter your choice (1-3): ")
    if choice == "1":
        add_record()
    elif choice == "2":
        display_records()
    elif choice == "3":
        print("Exiting program. Goodbye!")
        break
    else:
        print("Invalid choice! Please try again.")
📌 Simple Solution (Click to expand)

import csv


def add_record():
    name = input("Name: ")
    cls = input("Class: ")
    roll = int(input("Roll No: "))
    marks = int(input("Marks: "))
    with open("students.csv", "a", newline="") as fh:
        csv.writer(fh).writerow([name, cls, roll, marks])


def display():
    print("Start >----------")
    with open("students.csv", "r") as fh:
        for rec in csv.reader(fh):
            print(rec)
    print("End   >----------")


def menu():
    while True:
        print("1.Add Record | 2.Display | 3.Exit")
        ch = int(input("Enter your choice: "))
        if ch == 1:
            add_record()
        elif ch == 2:
            display()
        elif ch == 3:
            break
        else:
            print("Something went wrong")


menu()