CSV FILES
CSV FILES
INTRO:
CSV=Comma separated values
Used for storing tabular data as plain text in database or spread sheet
Each line=row/record
Each row may have more than 1 field/column
Fields are separated by commas
Extension= ‘.csv’
Human readable format
Need to import ‘csv module’ to read and write in the file
Syntax:
import csv
WRITING:
Writing mode=’w’
Step1:csv.writer(fileobject,delimiter=’ ,‘)= used to create a writerobject/csv
object(variable) to write contents into the csv file.
Step2: var1=[field1,field2…]
Step3: var2=[[row1],[row2]…..]
Step4:writerow()= used to write fieldnames and rows into the file.
Eg: csv.writerow(variable)
Step5:for loop to write rows into the file using writerow ()
Eg:
for i in var2:
csv.writerow(i)
OR
Use writerows()
Syntax: csv.writerows(var2)
newline=’ ‘ : used in open(…….) so that empty [] doesn’t printed along with
the o/p of rows
READING:
reading mode=’r’
Step1:csv.reader(fileobject)= reader object(variable) created
Step2:for loop in reader object to view rows.
EG:
NOTE:
If o/p rows are to be in comma sep values instead of lists
APPLICATIONS:
Faster
Small size
Easy to generate and import