You are on page 1of 28

CSV FILES

CSV FILES
CSV stands for Comma Separated Values.
CSV is just like a text file, in a human readable
format which is extensively used to store tabular
data, in a spreadsheet or database.
The separator character of CSV files is called a
delimiter. Default delimiter is comma(,). Other
delimiter are tab („/t‟), colon (:) , pipe(|), semi
colon (;) characters.
IT IS USED FOR STORING
CSV STANDS FOR
TABULAR DATA IN A
COMMA SEPARATED
SPREADSHEET OR
VALUES
DATABASE

EACH RECORD
CONSISTS OF FIELDS EACH LINE OF A FILE IS
SEPARATED BY A RECORD
COMMAS ( DELIMITER)
ADVANTAGES OF CSV FILES

EASIER TO CREATE

 PREFERRED IMPORT AND EXPORT


FORMAT FOR DATABASES AND
SPREADSHEETS

CAPABLE OF
STORING LARGE
AMOUNT OF DATA
PYTHON CSV MODULE

 csv module provide two type of objects :


Reader- to read form the csv files
Writer – to writhe in to the csv files
 To import csv module in our program, write the following
statement:
import csv
OPENING / CLOSING CSV FILES

 Open a csv file:


f=open(“stu.csv” , “w”)
OR
f=open(“stu.csv”, “r”)
 Close a csv file:
f.close()
ROLE OF ARGUMENT NEWLINE IN
OPENING OF CSV FILES
 Newline argument specifies how would Python handle
newline characters while working with csv files on
different operating systems
 Different operating systems store EOL characters
differently
EOL CHARACTERS USED IN DIFFERENT
OPERATING SYSTEMS
SYMBOL / MEANING OPERATING
CHAR SYSTEM
CR [\r] Carriage Return Macintosh
LF [\n] Line Feed UNIX
CR / LF [\r\n] Carriage Return / Line MS-DOS, Windows
Feed

NULL [\0] Null Character Other OSs


NOTE

Additional optional argument as newline =„‟(null


string no space in between) with file open() will
ensure that no translation of End of Line (EOL)
character takes place.
WRITING IN CSV FILES

csv.writer() Returns a writer object which


writes data into csv files
<WriterObject>.writerow() Writes one row of data on to
the writer object
<WriterObject>.writerows() Writes multiple rows on to the
writer object
ROLE OF WRITER OBJECT

The csv.writer() function returns a writer object


that converts the user‟s data into a delimited
string. This string can later be used to write into
CSV files using the writerow() function or
writerows() function
WRITING IN A CSV FILE USING WRITEROW() FUNCTION
import csv
f=open(“student.csv”, ”w”, newline=„ „)
swriter=csv.writer(f, delimiter=„;‟)
swriter.writerow([„Roll No‟, „Name‟, „Marks‟])
rec=[]
while True :
r=int(input(“Enter Roll Number : “))
n=input(“Enter Name : “)
m=int(input(“Enter Marks : “))
data=[r,n,m]
rec.append(data)
ch=input(“Do you want more records (y/n)”)
if ch==„n‟ or ch==„N‟:
break
for i in rec :
swriter.writerow(i) swriter.writerows(i)

f.close()
READING FROM CSV FILES

To read data from a CSV file, reader function of


csv module is used
csv.reader() – Returns a reader object. It loads
the data from CSV file into an iteratable after
parsing delimited data
STEPS TO READ DATA FROM A CSV FILE
 Import CSV module - import csv
 Open a CSV file in read mode - f=open(“stu.csv”,”r”)
 Create the reader object - sreader=csv.reader(f)
 Fetch data through for loop, row by row - for i in sreader :
print(i)
 Close the file - f.close()
HOW TO READ DATA FROM A CSV FILE

def read():
f=open(“student.csv”,”r”,newline=„\r\n‟)
sreader=csv.reader(f)
for i in sreader:
print(i)
f.close()
IMPORTANT QUESTIONS BASED ON CSV FILE

Write a program to write and read data


from a CSV file consisting Item No, Item
Name, Quantity and Price. Write a function
to search for a particular item using
itemcode.
import csv
def write():
f=open(“items.csv”, ”w”, newline=„ „)
swriter=csv.writer(f)
swriter.writerow([„Item No‟, „Item Name‟, „Qty‟, „Marks‟])
rec=[]
while True :
no=int(input(“Enter Item Number : “))
name=input(“Enter Item Name : “)
q=int(nput(“Enter quantity : “))
p=int(input(“Enter Price : “))
data=[ino,name,q,p]
rec.append(data)
ch=input(“Do you want more records (y/n)”)
if ch==„n‟ or ch==„N‟:
break
swriter.writerows(rec)
print(“Data written successfully”)
f.close()
def read():
f=open(“items.csv”,”r”,newline=„\r\n‟)
print(“Reading data from a CSV file”)
sreader=csv.reader(f)
for i in sreader:
print(i)
f.close()
def search(s):
f=open(“items.csv”,”r”)
print(“Searching data from a CSV file “)
s=input(“Enter item number to be searched :”)
found=0
sreader=csv.reader(f)
for i in sreader:
if i[0]==s:
print(i)
found=1
break
if found==0:
print(“Sorry ….No record found”)
Write a user defined function
search() to display those items
which are in the range of 10000
and 60000 (Both values included)
def search():
f=open(“items.csv”,”r”)
print(“Displaying records between 10000 and 60000”)
sreader=csv.reader(f)
next(sreader)
found=0
for i in sreader:
if int(i[3])>=10000 and int(i[3])<=60000:
print I
found=1
if found==0:
print(“Sorry…..No record found”)
f.close()
Write a functions to find the sum of
salary of all the Employees and count
the number of employees who are
getting salary more than 7000. The file
contains the data EmpNo, EmpName
and Salary
def sumsalary():
f=open(“emp.csv”,”r”)
sreader=csv.reader(f)
next(sreader)
sum=0
for i in sreader:
sum=sum+int(i[2])
print(“Sum of salary of all employees : “, sum)
f.close()
def slarygreater():
f=open(“emp.csv”,”r”)
sreader=csv.reader(f)
count=0
next(sreader)
for i in sreader:
if int(i[2])>7000:
count+=1
print(“Total employees having salary more than 7000”, count)
f.close()
OBJECTIVE TYPE QUESTIONS FOR CSV FILE
1. What does CSV stand for? ANS: Comma Separated Values
2. The function used to skip a row in a csv file is ……. ANS: next()
3. A CSV file is also knows as …… ANS: Flat File
4. Which of the following module is is provided by Python to do several operations
on csv files ANS: csv
5. What is the output of the following program?
import csv
d=csv.reader(open(“city.csv”))
next(d)
for row in d:
print(row)
If the file called “city.csv” contain the following details
Chennai, Mylapore
Mumbai, Andheri
ANS: Mumbai, Andheri
6. To specify a different delimiter while writing into a csv file ……… argument is
used with csv.writer. ANS: delimiter
7. The CSV file can only take comma(,) as delimiter (True/False)
8. The CSV files are text files (True/False)
9. ………..format is a text format accessible to all applications across several
platforms ANS : csv
10. ……….statement is given for importing csv module into your program
ANS: import csv
11. Comma is the default defaulter for a CSV file (True/False)
12. To read the data from a csv file …….. ANS: reader
13.CSV files are open with ……..argument to suppress EOL transalation
ANS : newline
14. For reading a data from a CSV file, …………………loads the data from the csv
file, parses it and makes it available in the form of an iterator where from the
records can be fetched row by row. ANS: csv.reader()
15. Identify the error in the following code:
import csv
f=open(“attendees2.csv”)
csv_f=csv.reader(f )
for row in csv_f:
print(row)

You might also like