Skip to main content

CSV SAMPLE PROJECT | MENU DRIVEN | 14 AUG

 

# -*- coding: utf-8 -*-

"""

Created on Thu Aug 14 13:21:08 2025


@author: Kirti Hora

"""

import csv

def createcsv():

    filename = "emp.csv"

    with open(filename, "w", newline="") as csv_fobj:

        wtr_obj = csv.writer(csv_fobj)

        wtr_obj.writerow(["Empno", "Name", "Basic Salary", "Allowance", "Deduction", "Net Salary"])

        while True:

            eno = input("Enter employee no: ")

            name = input("Enter name: ")

            bs = float(input("Enter basic salary: "))

            allowance = 2000

            dedn = bs * 0.05

            net = bs + allowance - dedn

            wtr_obj.writerow([eno, name, bs, allowance, dedn, net])

            ans = input("Want to enter another (y/n)? ").lower()

            if ans == "n":

                break

    print("CSV file created successfully!")


def displaycsv():  # UDF to display all records

    with open("emp.csv", "r") as csv_fobj:

        rdrobj = csv.reader(csv_fobj)

        for rec in rdrobj:

            print(rec)


def searcheno():  # UDF to search employee no

    with open("emp.csv", "r") as csv_fobj:

        eno = input("Enter Employee no to search: ")

        rdrobj = csv.reader(csv_fobj)

        found = False

        for rec in rdrobj:

            if rec[0] == eno:

                print(rec)

                found = True

                break

        if not found:

            print("Record not found")


def countall():  # UDF to count total records

    csv_fobj = open("emp.csv", "r")

    rdrobj = csv.reader(csv_fobj)

    totrec = 0

    for rec in rdrobj:

        totrec += 1

    csv_fobj.close()

    print("Total records -", totrec - 1)  # one record deducted for heading


def searchname():  # UDF to search on name

    with open("emp.csv", "r") as csv_fobj:

        nm = input("Enter Employee name to search: ")

        rdrobj = csv.reader(csv_fobj)

        ctr = 0

        for rec in rdrobj:

            if rec[1] == nm:

                print(rec)

                ctr += 1

        if ctr == 0:

            print("Record not found")


# Menu-driven program

ans = 'y'

while ans == 'y':

    print("\n1. Create the Employee CSV file")

    print("2. Display the details")

    print("3. Count total records")

    print("4. Search on basis of Employee no")

    print("5. Search on Employee name")


    ch = int(input("\nEnter choice: "))

    if ch == 1:

        createcsv()

    elif ch == 2:

        displaycsv()

    elif ch == 3:

        countall()

    elif ch == 4:

        searcheno()

    elif ch == 5:

        searchname()

    else:

        print("Wrong choice")


    ans = input("Want to continue (y/n)? ").lower()


Que 2: Write code to :

·       Stores Admno, Stud_Name, Marks, Percen in student.csv.

·       Allows searching records where Percen > 75.

 Sol:

import csv

# Function to add student data

def add_students():

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

        writer = csv.writer(f)

        writer.writerow(["Admno", "Stud_Name", "Marks", "Percen"])

       

        n = int(input("Enter number of students: "))

        for i in range(n):

            admno = input("Enter Admission No: ")

            name = input("Enter Student Name: ")

            marks = int(input("Enter Marks out of 100: "))

            percen = marks   # since marks out of 100 → percentage = marks

            writer.writerow([admno, name, marks, percen])

    print("Data written successfully!")

 

# Function to search students with percentage > 75

def search_students():

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

        reader = csv.reader(f)

        next(reader)  # skip header row

        print("\nStudents with Percentage > 75:")

        found = False

        for row in reader:

            if int(row[3]) > 75:

                print(row)

                found = True

        if not found:

            print("No student found with >75%")

 

# Main Program

add_students()

search_students()


Comments

Popular posts from this blog

GRADE XII - Python Connectivity with MySQL

  Python Connectivity with MySQL In real-life applications, the data inputted by the user and processed by the application needs to be saved permanently, so that it can be used for future manipulation. Usually, input and output data is displayed during execution but not stored, as it resides in main memory , which is temporary — i.e., it gets erased once the application is closed. This limitation can be overcome by sending the data to be stored in a database , which is made accessible to the user through a Front-End interface . Key Concepts Database A database is an organized collection of data that is stored and accessed electronically from a computer system. DBMS (Database Management System) A DBMS is software that interacts with end-users, applications, and the database to capture and analyze data. Front-End The Front-End is the user interface of the application, responsible for input/output interaction with the user. Back-End The Back-End refe...

GRADE XII - CSV FILE

CSV FILE (COMMA SEPERATED VALUE) CSV NOTES LINK :  CSV NOTES - CLICK HERE Writing data to a CSV file involves the following steps: Import the csv module Open the CSV file in write mode ( "w" ) using open() Create the writer object Write the data into the file using the writer object Close the file using close() writerow() Method This method is used to write a single row to a CSV file. It takes a sequence (list or tuple) as its parameter, and writes the items as a comma-separated line in the file. You do not need to add a newline character (\n) — it automatically places the end-of-line marker.     EXAMPLE 1: import csv  # Importing the csv module # CSV file opened using relative path csv_fobj = open("emp.csv", "w")   # Writer object created wtr_obj = csv.writer(csv_fobj) # Record with field heading is written wtr_obj.writerow(["Empno", "Name", "Salary"]) # Records with data are...