Working with CSV & Excel Files

  1. CSV

  2. Excel

Reading CSV Files:

Example 1:

# 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') 

Output:

Example 2:

['Sonam', '23', 'gurgaon', 'haryana', '9999222200']

['Arun', '65', 'patna', 'bihar', '7777222211']

['Nitin', '76', 'faridabad', 'haryana', '6666000011']

['Payal', '58', 'noida', 'up', '2222555599']

['Jyoti', '99', 'delhi', 'delhi', '4444555577']

Writing CSV Files:

Writing Dictionary to csv file

Reading an excel file using Python:

Output:

Extract number of rows in Excel:

Output:

4

Extract number of columns:

Output:

3

Extract a particular row value:

Output:

Extract First Column

Name

Rahul

Kapil

Creating/Writing in New Excel Workbook, Worksheet in Python

Reading all worksheet names and cells data of existing workbook:

Sheet

Sheet1

Sheet2

London

Australia

Iterating through Data

('gyansetu', 46, 976)

(324, 45, 57)

Reading data from a particular worksheet

Sheet

Sheet1

Sheet2

Hello

Students

Putting data in a Dictionary:

{2: {'parent': 'Shalki'}, 3: {'parent': 'Sanchi'}, 4: {'parent': 'Milanz'}, 5: {'parent': 'Anuj'}}

The code returns json format

{"2": {"parent": "Shalki"}, "3": {"parent": "Sanchi"}, "4": {"parent": "Milanz"}, "5": {"parent": "Anuj"}}

Appending Excel/New data

Insert/Delete Row & Column

Reading/Creating/Renaming Excel Worksheets

Adding Filters:

Filters and sorts can only be configured by openpyxl but will need to be applied in applications like Excel. This is because they actually rearranges or format cells or rows in the range.

Excel Formulas

Adding Charts

Ref:- https://realpython.com/openpyxl-excel-spreadsheets-python/arrow-up-right

Last updated

Was this helpful?