Working with CSV & Excel Files
Reading CSV Files:
# importing csv module
import csv
# csv file name
filename = "C:/Users/Shalki/Desktop/python/Book1.csv"
# initializing the titles and rows list
fields = []
rows = []
# reading csv file
with open(filename, 'r') as csvfile:
# creating a csv reader object
csvreader = csv.reader(csvfile)
# extracting field names through first row
fields = next(csvreader)
# extracting each data row one by one
for row in csvreader:
rows.append(row)
# get total number of rows
print("Total no. of rows: %d"%(csvreader.line_num))
# printing the field names
print('Field names are:' + ', '.join(field for field in fields))
# printing first 5 rows
print('\nFirst 5 rows are:\n')
#print(rows[1])
for row in rows[:5]:
# parsing each column of a row
for cell in row:
print("%10s"%cell, end="\t")
print('\n')

Writing CSV Files:
Writing Dictionary to csv file
Reading an excel file using Python:
Output:
Extract number of rows in Excel:
Output:
Extract number of columns:
Output:
Extract a particular row value:
Last updated