CSV file reading:
- CSV Stands for “Comma Separated Values”
- CSV is an alternate to MS-Excel sheet
- Text file always stores textual information. It is not recommended to store and process record type information using Text File.
- CSV file stores information in tabular form(Rows and Columns)
Creating data.csv file:
- Open notepad file.
- Write records information by separating with comma
- 101,amar,5000
- 102,annie,8000
- 103,hareen,7500
- 103,satya,6500
- Save the file with .csv extension
- Close the file and re-open the file.
- File will be opened with MS-Excel software by default.
data.csv file:
Read information of CSV file:
“csv”:
- A pre-defined module belongs to python library.
- It is providing pre-defined functionality to process the information of CSV file.
- Reader() is a method belongs to csv module
- Reader() method returns the CSV file data as an Object to process.
Code:
import csv
class ReadCSV:
file = None
def main():
try:
ReadCSV.file = open("./data.csv" , "r")
print("File opened")
table = csv.reader(ReadCSV.file)
print("Records are :")
for record in table:
print(record)
except Exception as e:
print("Exception :", e)
finally:
if ReadCSV.file != None:
ReadCSV.file.close()
print("File closed")
return
ReadCSV.main()
Using nested for loop, we can split the record into fields also:
table = csv.reader(ReadCSV.file)
print("Records information :")
for record in table:
for field in record:
print(field)
Construct Dictionary object from CSV file:
- Create one CSV file with account details.
- Read CSV file
- Create an Empty dictionary
- Define a class with identity Account.
- Construct Account object and update the object into dictionary.
- Finally, when we specify the account number(key), we have to display value(account details).
accounts.csv file:
Account.py:
import csv
class Account:
def __init__(self, accno, name, balance):
self.accno = accno
self.name = name
self.balance = balance
return
Bank.py:
class Bank:
accs_dict = dict()
def details():
while True:
num = int(input("Enter account number : "))
try:
record = Bank.accs_dict.get(num)
print("Details are :")
print("Name : ", record.name)
print("Balance :", record.balance)
except Exception as e :
print("Exception :", e)
ch = input("Do you want to check another record(y/n) : ")
if ch=='n':
break
return
CSVToDict.py:
class CSVtoDict:
file = None
def main():
try:
CSVtoDict.file = open("./accounts.csv" , "r")
print("File opened")
table = csv.reader(CSVtoDict.file)
for record in table:
num = int(record[0])
name = record[1]
balance = int(record[2])
obj = Account(num, name, balance)
Bank.accs_dict.update({num : obj})
print(record , " updated to dictionary")
Bank.details()
except Exception as e:
print("Exception :", e)
finally:
if CSVtoDict.file != None:
CSVtoDict.file.close()
print("File closed")
return
CSVtoDict.main()
Output:
File opened
['1001', 'amar', '5000'] updated to dictionary
['1002', 'annie', '8000'] updated to dictionary
['1003', 'hareen', '7500'] updated to dictionary
['1004', 'satya', '9000'] updated to dictionary
Enter account number : 1002
Details are :
Name : annie
Balance : 8000
Do you want to check another record(y/n) : y
Enter account number : 1004
Details are :
Name : satya
Balance : 9000
Do you want to check another record(y/n) : n
File closed
Write code for following: