CSV FILE
(COMMA SEPERATED VALUE)
CSV NOTES LINK :
Writing data to a CSV file involves the following steps:
-
Import the
csv
module -
Open the CSV file in write mode (
"w"
) usingopen()
-
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 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
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
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
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"])
rec = []
eno =
int(input("Enter employee no: "))
name =
input("Enter name: ")
bs =
float(input("Enter basic salary: "))
allowance = 2000
dedn =
bs * 0.05
net = bs
+ allowance - dedn
rec.append([eno, name, bs, allowance, dedn, net])
if ans
== "n":
break
wtr_obj.writerows(rec)
print("CSV file created successfully!")
Comments
Post a Comment