Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
4 views30 pages

11 - Python CSV Files

Uploaded by

myth87654321
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)
4 views30 pages

11 - Python CSV Files

Uploaded by

myth87654321
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
You are on page 1/ 30

Computer Science

CLASS-XII (Code No. 083)

DPS RKP Computer Science Department


Data Files - 3 (CSV Files)

2021-2022
Python Data Files - 3
Data Files - CSV file
● CSV file: import csv module, open / close csv file,
● write into a csv file using csv.writerow() and read from a csv file

DPS RKP Computer Science Department


using csv.reader( )

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.

CONTENT IN NOTEPAD/TEXT EDITOR CONTENT IN SPREADSHEET TOOL

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.

PRODUCT.CSV MEMBER.CSV

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:

csv.reader() - 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> = csv.reader(<CSVFileObject>, delimiter=',')

7
reader() method of csv module
CLASS.CSV
import csv "Class", "Strength"
with open("CLASS.CSV","r") as cF: "A", "40"
cV = csv.reader(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:

csv.writer() - 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>=csv.writer(<CSVFileObject>, delimiter=',')
<WriterObj>.writerow(<List Content>)

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

DPS RKP Computer Science Department


cV.writerow(['A', 40])
cV.writerow(['B', 38])
cV.writerow(['C', 39])
cV.writerow(['D', 36])

Recs=[['Class','Strength'],['A','40'],['B','38'],['C','39'],['D','36']]
cV = csv.writer(cF, delimiter=',',newline="")
for c in Recs:
cV.writerow(c)

10
Function to Create a new CSV File
def ProductsSave():
with open('products.csv', 'a', newline="") as cF:
cW = csv.writer(cF)
cW.writerow(['Product', 'Price','Qty'])

DPS RKP Computer Science Department


cW.writerow(['Ball Pen', 30,2000])
cW.writerow(['Eraser', 8,1500])
cW.writerow(['Sharpener',15,800])
cW.writerow(['U Clip',5,3000])
While working in IDLE, writing this
will be must otherwise it will insert
an empty [] line due to newline
character as default.
In colab, it can be skipped 11
Function to View content from a CSV File
def CSVView():
try:
with open('products.csv', 'r') as cF:

DPS RKP Computer Science Department


cR = csv.reader(cF)
for r in cR:
print(r)
except FileNotFoundError:
print("products.csv File Not Found")

12
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")

13
CSV file for BOOK List
Write a Python code with the following functions.

● Create a new CSV file containing Book List


● Adding new content at the bottom of a CSV file

DPS RKP Computer Science Department


● Viewing the content of a CSV file
● Search for a record matching with Book ID
● Find costly books (i.e., Price more than 500) from a CSV file

14
Adding Data in new CSV file
def New():
with open('books.csv','w', newline="") as cF:
cW =csv.writer(cF)
while True:

DPS RKP Computer Science Department


ID =input("ID:")
Title =input("Title:")
Price=input("Price:")
Book=[ID,Title,Price]
cW.writerow(Book)
Q=input("More(Y/N)?")
if Q=='N':
break

15
Adding Data in an existing CSV file
def AddMore():
with open('books.csv','a', newline="") as cF:
cW =csv.writer(cF)
while True:

DPS RKP Computer Science Department


ID =input("ID:")
Title =input("Title:")
Price=input("Price:")
Book=[ID,Title,Price]
cW.writerow(Book)
Q=input("More(Y/N)?")
if Q=='N':
break

16
Viewing Data from a CSV File
def ViewAll():
try:
with open('books.csv','r') as cF:
cR=csv.reader(cF)

DPS RKP Computer Science Department


for L in cR:
print(L)
except FileNotFoundError:
print("File Not Found")

17
Search for a Record matching with ID from a CSV file
def Search():
try:
with open('books.csv','r') as cF:
cR=csv.reader(cF)

DPS RKP Computer Science Department


IDS=input("ID to search:")
for L in cR:
if IDS==L[0]:
print(L)
break
else:
print("Book",IDS,"Not Found!")
except FileNotFoundError:
print("File Not Found")

18
Viewing Books which are costly than 500 from CSV file
def CostlyBooks():
try:
with open('books.csv','r') as cF:
cR=csv.reader(cF)

DPS RKP Computer Science Department


CB=0
for L in cR:
if int(L[2])>500:
print(L)
CB+=1
print(CB,"Books priced more than 500")
except FileNotFoundError:
print("File Not Found")

19
Navigating through all the options of CSV file
while True:
Opt=input("1:New 2:Add More 3:ShowCSV\n \
4:Search 5:Costly Books 6:Quit ")
if Opt=="1":

DPS RKP Computer Science Department


New()
elif Opt=="2":
AddMore()
elif Opt=="3":
ShowAll()
elif Opt=="4":
Search()
elif Opt=="5":
CostlyBooks()
else:
break
20
Navigating through options - output screens
1:New 2:Add More 3:ShowCSV
4:Search 5:Costly Books 6:Quit 1
ID:10
ID:14
Title:Jack King
Title:Lie and Truth

DPS RKP Computer Science Department


Price:304
Price:400
More(Y/N)?Y
More(Y/N)?Y
ID:11
ID:18
Title:Story of 1
Title:Playing with Numbers
Price:230
Price:100
More(Y/N)?Y
More(Y/N)?Y
ID:19
Title:Jack - the Man
Price:600
More(Y/N)?N
21
Navigating through options - output screens
1:New 2:Add More 3:ShowCSV
4:Search 5:Costly Books 6:Quit 3
['10', 'JK', '304']
['11', 'Story of 1', '230']

DPS RKP Computer Science Department


['14', 'Lie and Truth', '400']
['18', 'Playing with Numbers', '100']
['19', 'Jack - the Man', '600']
1:New 2:Add More 3:ShowCSV
4:Search 5:Costly Books 6:Quit 2
ID:21
Title:India Shining
Price:3200
More(Y/N)?N

22
Navigating through options - output screens
1:New 2:Add More 3:ShowCSV
4:Search 5:Costly Books 6:Quit 4
ID to search:19
['19', 'Jack - the Man', '600']

DPS RKP Computer Science Department


1:New 2:Add More 3:ShowCSV
4:Search 5:Costly Books 6:Quit 5
['19', 'Jack - the Man', '600']
['21', 'India Shining', '3200']
2 Books priced more than 500
1:New 2:Add More 3:ShowCSV
4:Search 5:Costly Books 6:Quit 6

23
Create new - All rows to be written in one go
def Save():
with open('books1.csv','w',newline="") as cF:
cW =csv.writer(cF)
B=[]

DPS RKP Computer Science Department


while True: In CSV file, both the
ID =input("ID:") methods can be used for
Title =input("Title:") creating CSV file, there
Price=input("Price:") will be no difference in
B.append([ID,Title,Price]) the methods for reading.
Q=input("More(Y/N)?") (i) writerow()
(ii) writerows()
if Q=='N':
break
cW.writerows(B) writerows() - will write
all rows in one go
24
Add new - All rows to be written in one go
def AddMore():
with open('books1.csv','a',newline="") as cF:
cW =csv.writer(cF)
B=[]

DPS RKP Computer Science Department


while True:
In CSV file, both the
ID =input("ID:")
methods can be used for
Title =input("Title:")
creating CSV file, there
Price=input("Price:") will be no difference in
B.append([ID,Title,Price]) the methods for reading.
Q=input("More(Y/N)?") (i) writerow()
if Q=='N': (ii) writerows()
break
cW.writerows(B) writerows() - will write
all rows in one go
25
Case Study 1 - Books Organization System
Write a Python Code with the following Options using user-defined functions:
1. To add new Book
2. To Search for a Book on the basis of Bno
3. To Search for a Book on the basis of Title

DPS RKP Computer Science Department


4. To Search for a Book on the basis of Author
5. To display books of a particular type
6. To count number of books under each type
7. To arrange and display the details of books in ascending order of Title of
the books
8. To modify Type of a book (with matching BNO)
9. To view details/list of of all the Books
10. To transfer the books of type “FICTION” to another file “FICTION.CSV”
BOOKS.CSV
26
Case Study 2 - Banking Accounts Management System
Assuming “Global Money Bank” maintains the following data of its customers:

ACNO - Account Number


NAME - Customer Name

DPS RKP Computer Science Department


MOBILE - Customer Mobile
BALANCE - Customer Balance Amount in Bank
TRANS - Transaction Type['D'-Deposit, 'W'-Withdrawal, 'I':Interest]
TDATE - Transaction Date
BANK.CSV

27
Case Study 2 - Banking Accounts Management System
Write a Python Code with the following Options using user-defined functions:
1. To add new Customer
2. To Search for a customer on the basis of Accno
3. To modify mobile number of customer (with matching account number)

DPS RKP Computer Science Department


4. To allow deposit money from a customer’s account by searching for a
particular customer’s data matching with an Accno and updating (adding in
the balance) the same and changing the TRDATE (and TRANS to ‘D’)
5. To allow withdraw money from a customer’s account by searching for a
particular customer’s data matching with an Accno and updating
(subtracting from the balance) of the same by subtracting the amount
from Balance and updating the TRDATE (if and only if the customer has
sufficient balance to allow withdraw) (and TRANS to ‘W’)
6. To view all the content of customers BANK.CSV
28
Function to Update Mobile
def MobileUpdate(): r+ To allow read as well
try: as write in CSV file
with open("BANK.CSV","r+") as F:
CB=csv.reader(F) else:

DPS RKP Computer Science Department


ACNS=input("Acno:") F.truncate(0)
AB=[];U=0 F.seek(0)
for B in CB: CWB=csv.writer(F)
if ACNS==B[0]: CWB.writerows(AB)
print("Name:"+B[1]\ except FileNotFoundError:
,"Present Mobile No:"+B[2]) print("File Not Found!!!")
B[2]=input("New No:")
U+=1
AB.append(B)
if U==0:
print("Acno",ACNS,"not found!!!")
29
Happy Learning…

DPS RKP Computer Science Department


Thank you!
Department of Computer Science

30

You might also like