0% found this document useful (0 votes)
3 views20 pages

Python CSV Files

The document provides an overview of working with CSV (Comma-Separated Values) files in Python, detailing how to read from and write to these files using the csv module. It explains the structure of CSV files, including how to handle commas within data, and outlines different modes for opening files. Additionally, it includes sample functions for creating and viewing CSV files with user-provided data.

Uploaded by

Mehul Srivastava
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views20 pages

Python CSV Files

The document provides an overview of working with CSV (Comma-Separated Values) files in Python, detailing how to read from and write to these files using the csv module. It explains the structure of CSV files, including how to handle commas within data, and outlines different modes for opening files. Additionally, it includes sample functions for creating and viewing CSV files with user-provided data.

Uploaded by

Mehul Srivastava
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Computer Science

CLASS-XII (Code No. 083)

DPS RKP Computer Science Department


Data Files - 3 (CSV Files)

2022-2023
Python Data Files - 3
Data Files - CSV file
● CSV file: import csv module, open / close csv file,
● write into a csv file using [Link]() and read from a csv file

DPS RKP Computer Science Department


using [Link]( )

2
Data File - CSV Files
CSV File
Comma-Separated Values (CSV) file is a delimited Text File that uses a comma
to separate values. In CSV file, each line of the file is considered as a data

DPS RKP Computer Science Department


record and each record consists of one or more fields, separated by commas. In
CSV files, comma is used as a field separator. It is a PLATFORM independent file.

CONTENT IN NOTEPAD/TEXT EDITOR CONTENT IN SPREADSHEET TOOL

Can be
easily used
to port data
from one
system to
another
having
different OS
3
Data File - CSV Files
“A CSV file (Comma Separated Values file) is a type of plain text file that uses
specific structuring to arrange tabular data. Because it is a plain text file, it can
contain only actual text data—in other words, printable ASCII or Unicode
characters”.

DPS RKP Computer Science Department


Reading/Writing data in CSV files is a common and simple way to share organized
information between programs. CSV is the most popular format for exchanging
data nowadays as it can be directly used in text editors, spreadsheet tools and
databases.

Let us learn how to read, process, and parse CSV from text files using Python.

4
Data File - CSV Files
CSV files use a comma to separate each specific data value. But if comma (,) itself
is the content, we can enclose it inside quotes.

[Link] [Link]

DPS RKP Computer Science Department


Code, Item, Price MNO, MEM NAME, ADDRESS
101, Ball Pen, 30 3001, "Sultan Shah", "59,ABC NGR"
105, Eraser, 15 3002, "Ravi Jha", "45,JRC CLY"
102, Fountain Pen, 68 3004, "Zia Khan", "A-21,PP Lane"
103, Sharpener, 22 3009, "Aryan Sen", "U-2, Senpur"

5
CSV File Modes
Read Mode - To read the content from an existing CSV File. Raises
r exception FileNotFoundError, if the file does not exist

Write Mode - To allow user to write the content on a new CSV

DPS RKP Computer Science Department


w File. If the file already exists it will be overwritten.

Append Mode - To allow user to write the content at the end of an


a an existing CSV File. If the file does not exist, it will create a new
one.

Update Mode (reading as well as writing)- To allow user to read as


r+ well write the content on an existing CSV File.

6
Opening and Reading from CSV file
Opening of CSV file will be exactly same as a text file.

However, methods for reading from CSV file and writing on the CSV file will be
different from a text file.

DPS RKP Computer Science Department


For reading the content from a CSV file, we will use the following:

[Link]() - Method required for reading content from a CSV file. It will
work only when CSV file is opened as a text file in "r" mode.

import csv
with open(<FileName>,<Mode>) as <CSVFileObject>:
<ReaderObj> = [Link](<CSVFileObject>, delimiter=',')

7
reader() method of csv module
[Link]
import csv "Class", "Strength"
with open("[Link]","r") as cF: "A", "40"
cV = [Link](cF, delimiter=',') "B", "38"

DPS RKP Computer Science Department


print(next(cV)) "C", "39"
print(next(cV)) "D", "36"
for c in cV:
print(next(cV))
print(next(cV)) print(c)
['Class', 'Strength']
print(next(cV)) ['A', '40']
['B', '38']
['C', '39']
['D', '36']

8
writer() method of csv module
For writing the content on a CSV file, we will use the following:

[Link]() - Method required for writing content into a CSV file. It will only
work when CSV file is opened as a text file in "w" or "a" mode.

DPS RKP Computer Science Department


with open(<FileName>,<Mode>,newline="") as <CSVFileObject>:
<WriterObj>=[Link](<CSVFileObject>, delimiter=',')
<WriterObj>.writerow(<List Content>)

9
writer() method of csv module
import csv
with open("[Link]","w",newline="") as cF:
cV = [Link](cF, delimiter=',')
[Link](['Class', 'Strength'])

DPS RKP Computer Science Department


[Link](['A', 40])
[Link](['B', 38])
[Link](['C', 39])
[Link](['D', 36])

Recs=[['Class','Strength'],['A',40],['B',38],['C',39],['D',36]]
cV = [Link](cF, delimiter=',’)
for c in Recs:
[Link](c)

10
Creating of CSV file with fixed Data and

DPS RKP Computer Science Department


Viewing the same
using two separate functions

11
Function to Create a new CSV File - Alternative 1
import csv
def ProductsSave():
with open('[Link]', 'a', newline="") as cF:
cW = [Link](cF)

DPS RKP Computer Science Department


[Link](['Product', 'Price','Qty'])
[Link](['Ball Pen', 30,2000])
[Link](['Eraser', 8,1500])
[Link](['Sharpener',15,800])
[Link](['U Clip',5,3000])
While working in IDLE, writing this
will be must otherwise it will insert
writerow - for writing one single list/row an empty [] line due to newline
at a time character as default.
In colab, it can be skipped 12
Function to Create a new CSV File - Alternative 2
import csv
def ProductsSave():
with open('[Link]', 'a', newline="") as cF:
cW = [Link](cF)

DPS RKP Computer Science Department


[Link]([['Product', 'Price','Qty'],\
['Ball Pen', 30,2000],\
['Eraser', 8,1500],\
['Sharpener',15,800],\
['U Clip',5,3000]]) While working in IDLE, writing
this will be must otherwise it will
writerows - for writing nested insert an empty [] line due to
list/mutiple rows at a time newline character as default.
In colab, it can be skipped 13
Function to View content from a CSV File
def CSVView():
try:
with open('[Link]', 'r') as cF:

DPS RKP Computer Science Department


cR = [Link](cF)
for r in cR:
print(r)
except FileNotFoundError:
print("[Link] File Not Found")

14
Navigating through ProductsSave() and CSVView()
while True:
OPT=input("A:Add V:View Q:Quit")
if OPT in ['a','A']:
ProductsSave()

DPS RKP Computer Science Department


elif OPT in ['v','V']:
CSVView()
elif OPT in ['q','Q']:
print("Thanks");break
else:
print("Invalid Option")

15
Creating of CSV file with user provided

DPS RKP Computer Science Department


Data and Viewing the same
using two separate functions

16
Function to Create a new CSV File with User Data
import csv
def ProductsSave():
with open('[Link]', 'a', newline="") as cF:
cW = [Link](cF)

DPS RKP Computer Science Department


[Link](['Product', 'Price','Qty'])
while True:
Product=input("Product:")
Price=input("Price:")
Qty=input("Qty:")
[Link]([Product, Price, Qty])
More=input("More(Y/N)?")
if More in ['n','N']:
break

17
Function to View customized content from a CSV File
def CSVView():
try:
with open('[Link]', 'r') as cF:
cR = [Link](cF)

DPS RKP Computer Science Department


print("PRODUCT PRICE QTY")
for r in cR:
print(r[0],r[1],r[2])
except FileNotFoundError:
print("[Link] File Not Found")

18
Navigating through ProductsSave() and CSVView()
while True:
OPT=input("A:Add V:View Q:Quit")
if OPT in ['a','A']:
ProductsSave()

DPS RKP Computer Science Department


elif OPT in ['v','V']:
CSVView()
elif OPT in ['q','Q']:
print("Thanks");break
else:
print("Invalid Option")

19
Happy Learning…

DPS RKP Computer Science Department


Thank you!
Department of Computer Science

20

You might also like