Skip to main content

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:

  1. Import the csv module

  2. Open the CSV file in write mode ("w") using open()

  3. Create the writer object

  4. Write the data into the file using the writer object

  5. 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 written

wtr_obj.writerow([1, "Akash", 60000])

wtr_obj.writerow([2, "Manshi", 75000])

# CSV file closed

csv_fobj.close()


EXAMPLE 2:(USING WHILE LOOP)

import csv  

# Open CSV file for writing

csv_fobj = open("emp.csv", "w", newline="")  

# Create writer object

wtr_obj = csv.writer(csv_fobj)

# Write field headings

wtr_obj.writerow(["Empno", "Name", "Salary"])

# Loop to accept employee records

ans = 'y'

while ans.lower() == 'y':

    empno = input("Enter Employee no: ")

    name = input("Enter name: ")

    salary = float(input("Enter Salary: "))

    wtr_obj.writerow([empno, name, salary])

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


# Close file

csv_fobj.close()

print("Data written to emp.csv successfully!")


writerows() Method

  • This method is used to write multiple rows to a CSV file at once.

  • The writerows() method takes a sequence (such as a nested list or nested tuple) as its parameter, and writes each inner sequence as a comma-separated line in the file.

  • Just like writerow(), you do not need to manually add a newline character (\n) or any other end-of-line indicator — it automatically handles line breaks as needed


EG:

import csv

# Open CSV file in write mode
csv_fobj = open("stud.csv", "w", newline="")

# Create writer object
wtr_obj = csv.writer(csv_fobj)

# Write multiple rows
wtr_obj.writerows([
    [1, "Anu", 98],
    [2, "Sam", 75],
    [3, "Soni", 89]
])

# Close the file
csv_fobj.close()


Reading CSV File in Python

import csv

# Open the CSV file in read mode
with open("emp.csv", "r") as csv_fobj:
    # Create reader object
    rdrobj = csv.reader(csv_fobj)
    
    # Read and print each record
    for rec in rdrobj:
        print(rec)

OR
import csv

csv_fobj = open("emp.csv", "r")  # file opened in read mode
rdrobj = csv.reader(csv_fobj)    # reader object created

for rec in rdrobj:
    print(rec)  # print each record

csv_fobj.close()  # close the file


QUE:Write a function countrec() to count the number of records present in the csv file.

import csv

def countrec():

    csv_fobj = open("emp.csv", "r")  # file opened in read mode

    rdrobj = csv.reader(csv_fobj)    # reader object created

    next(rdrobj)  # skip the heading row

    ctr = 0

    for rec in rdrobj:

        ctr += 1

    print("Number of records:", ctr)

    csv_fobj.close()  # close the file

QUE 2:

Write a Python program to create a CSV file by accepting Employee Number, Name, and Basic Salary from the user repeatedly until the user decides to stop.

The program should: Calculate Deduction as 5% of the basic salary.

Set Allowance as 2000.

Calculate Net Salary as:  Net Salary=Basic Salary+Allowance−Deduction

Store all details in a CSV file with the following column headers:

Empno, Name, Basic Salary, Allowance, Deduction, Net Salary

Sol:

import csv

 filename = input("Enter filename with .csv extension: ")

 # Open CSV file in write mode

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

    wtr_obj = csv.writer(csv_fobj)

     # Write header row

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

     # List to store all records

    rec = []

     while True:

        eno = int(input("Enter employee no: "))

        name = input("Enter name: ")

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

         # Calculations

        allowance = 2000

        dedn = bs * 0.05

        net = bs + allowance - dedn

         # Append the record

        rec.append([eno, name, bs, allowance, dedn, net])

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

        if ans == "n":

            break

     # Write all records to file

    wtr_obj.writerows(rec)

print("CSV file created successfully!")


Comments

Popular posts from this blog

PYTHON - MYSQL CONNECTIVITY CODE

  #INSERTION OF DATA import mysql.connector mydb = mysql.connector.connect( host="localhost", user="root", passwd="root", database="school" ) print("Successfully Connected") #print(mydb) mycursor=mydb.cursor()   v1=int(input("enter ID:")) v2=input("enter name:") v3=input("enter Gender:") v4=int(input("enter age:")) sql='insert into TEACH values("%d","%s","%s","%s")'%(v1,v2,v3,v4) print(sql) mycursor.execute(sql) mydb.commit() print("record added") #MYSQL Connection code – Deletion on database SOURCE CODE: s=int(input("enter id of TEACHER to be deleted:")) r=(s,) v="delete from TEACH where id=%s" mycursor.execute(v,r) mydb.commit() print("record deleted") MYSQL Connection code – Updation on database SOURCE CODE: import mysql.connector mydb = mysql.connector.c...

REVISION IF CONSTRUCT | CLASS TEST

                                                                                     CLASS TEST 1. Write a Python program that asks the user for their age, gender, and current fitness level (beginner, intermediate, or advanced). Based on this information, suggest a suitable fitness plan using if-else statements. Requirements: Inputs : Age (integer) Gender (male/female) Fitness level (beginner/intermediate/advanced) Outputs : Recommend a fitness plan that includes: Suggested workout duration. Type of exercises (e.g., cardio, strength, flexibility). Rest days. Logic : Use if-else to determine the plan based on conditions such as: Age group (e.g., <18, 18–40, >40). Fitness leve...