Csv-File-Ppt-Intro
Csv-File-Ppt-Intro
a spreadsheet or database.
Files in the C S V format can be imported to and exported from
programs that store data in tables, such as Microsoft Excel or
OpenOffice Calc.
C S V stands for "comma-separated values“.
Each line of the file is a data record. Each record consists of one or
more fields, separated by commas. The use of the comma as a field
separator is the source of the name for this file format
2
3
4
“
◗ CSV is faster to
• CSV is smaller in size.
handle.
•CSV is easy to generate and import
onto a spreadsheet or database.
•CSV is human readable and easy
to edit manually.
• CSV is simple to implement and
parse.
•CSV is processed by almost all
5
6
Python provides a module to deal with these variations
called the csv module
This module allows you to read spreadsheet info into
our program
We load the module in the usual way using import:
7
A CSV file stores tabular data (numbers and text) in plain text.
* Each line of the file is a data record.
* Each record consists of one or more fields, separated by
commas.
* CSV files allows to choose a different delimiter character such as
Syntax:
fh=open(“stu.csv”,”w”)- to open the file in write mode
fh=open(“stu.csv”,”r”)- to open the file in write mode
9
* Import csv module
* Open csv file in a file handle
*Create a reader object by using csv.reader() function
Example: stureader=csv.reader(fh)
*using for loop fetch the data from the reader object
in which data is stored in the form of iterable
10
import csv
f=open("d:/marks.csv",'r')
csvr = csv.reader(f )
for row in csvr:
print(row)
f.close()
11
Import csv module
* Open csv file in a file handle( just as text file)
Example : fh=open(“stu.csv”,”w”)- to open the file in
write mode
*Create a writer object by using csv.writer()
function. Ex. stuwriter=csv.writer(fh)
* Obtain user data and form a Python sequence
(list or tuple) out of it.
Ex. sturec=(11, ‘Neelam’,79.0)
*Write the Python sequence onto the writer
object using csv.writerow() or csv.writerows()
Ex. stuwriter.writerow(sturec)
1
Write to a CSV file
import csv
with open('protagonist.csv', 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["SN", "Movie", "Protagonist"])
writer.writerow([1, "Lord of the Rings", "Frodo Baggins"])
writer.writerow([2, "Harry Potter", "Harry Potter"])
13
Writing multiple rows with writerows()
import csv
csv_rowlist = [["SN", "Movie", "Protagonist"],
[1, "Lord of the Rings", "Frodo Baggins"],
[2, "Harry Potter", "Harry Potter"]]
with open('protagonist.csv', 'w') as file:
writer = csv.writer(file)
writer.writerows(csv_rowlist)
14
CSV FILE
15
16