0% found this document useful (0 votes)
13 views6 pages

CSV Files-Notes (1)

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 6

CSV Files-Introduction

 CSV stands for Comma Separated Values.


 It is just like a text file, which is in a human readable format, that can be
extensively used to store tabular data in spreadsheet or a database.
 The separator character called delimiter, by default, is comma and other
delimiters are tab(‘\t’),colon(:),semicolon(;) etc…
 Each line of a file is called Record.
 Each record consists of Fields, separated by Commas.

Advantages:
 Easier to create.
 Mostly used for importing & exporting data to and from the database.
 Capable of storing large amount of data.
CSV Module
 CSV module provides 2 objects:
1) writer: to write in to the CSV files
2) reader: to read data from the CSV files.
 To import CSV module in our program, write the following statement:
import csv or from csv import *
 Opening a CSV files:
f=open(“student.csv”,”w”) # open file in the write mode and newline
argument is optional by default its value is
‘\n’.
‘’:null string indicates no space in between.
OR
f=open(“student.csv”,”r”) # open file in a read mode.
 Closing of CSV files:
f.close()
Writing in CSV files
csv. writer() Returns a writer object
which writes data in to csv
files.
<writer_object>. Writes one row of data on to
writerow() writer object.
<writer_object>. Writes multiple rows on to the
writerows() writer object.

* csv.writer() function returns a writer object which


converts user data in to string. This string can be used to
write in to csv files using writerow() or writerows()
function.
Writing in to CSV file using writerow():
import csv
f=open(“student.csv”,”w”,newline=‘ ’)
w=csv.writer(f)
w.writerow([‘RollNo’,’Name’,’Marks’])
rec=[]
while True:
r=int(input(“Enter Roll Number:”))
n=input(“Enter your Name:”)
m=int(input(“Enter your Marks:”))
record=[r,n,m]
rec.append(record)
ch=input(“Do you want to add more records?y/n”)
if ch==‘n’ or ch==‘N’:
break
for i in rec:
w.writerow(i)
f.close()
Writing in to CSV file using writerows():
import csv
f=open(“student.csv”,”w”,newline=‘\n’)
w=csv.writer(f)
w.writerow([‘RollNo’,’Name’,’Marks’])
rec=[]
while True:
r=int(input(“Enter Roll Number:”))
n=input(“Enter your Name:”)
m=int(input(“Enter your Marks:”))
record=[r,n,m]
rec.append(record)
ch=input(“Do you want to add more records?y/n”)
if ch==‘n’ or ch==‘N’:
break
w.writerows(rec)
f.close()
Reading data from csv files:
 To read data from csv files, reader() function of csv module is used.
 It returns a reader object.
 It loads data from csv files.

How to read data from csv file:


import csv
f=open(“student.csv”,”r”)
r=csv.reader(f)
for i in r: # fetch data through for loop row by row.
print(i)
f.close()

You might also like