How to perform excel operations using Python|CSV file operation using python|how to perform input and retrieve data from csv/excel files using python

Introduction

In this blog We are going to perform some operation on Excel spreadsheets using Python program.
 

CSV Files

To understand how to perform Excel sheet operations we have to first learn about  csv files.CSV files (Comma separated files) are text files which contain comma(" , ") instead of space(" _ ").In easy word each value or word is separated with a comma.The comma is known as "delimiter".
For example.
Text file :- THIS IS A SAMPLE FILE
CSV File:-THIS, IS, A, SAMPLE, FILE

First program:-How to write data in csv file and then read them using python program.

Understanding the flow of code:-

  • importing csv module
  • Defining write() and read() function
  •  Opening the file and establishing the connection.
  • Accepting data from user 
  • using writer object to input data in spreadsheet.
  • for reading the data we use reader object

Source code

import csv
def write():
f=open("Items.csv","w",newline="")
k=csv.writer(f)
k.writerow(["Itemno.","itemName"])
bec=[]
while True:
In=int(input("enter item number :"))
Iname=input("enter name of item :")
Ist=[In, Iname]
bec.append(Ist)
ch=input("want to enter more records ?y/n:")
if ch=='n':
break
for i in bec:
k.writerow(i)
f.close()
def read():
f=open("Items.csv","r")
l=csv.reader(f)
for i in l:
print(i)
write()
read()
#code ended

About the code

This code opens a new file if the files is not found in the directory with the preferred name.The code continues the loop until it is terminated by the user.

Output screens:-

Click for full resolution image


Code to read the data.

Source code:-

import csv 
file=open("Items.csv","r",newline='\r\n')
read=csv.reader(file)
a=next(read)
itemno=int(input("enter item no. to be searched:"))
for i in read:
if int(i[0])==itemno:
print(i[1])
break
if int(i[0])!=itemno:
print("error")
#Code ended

Output

Click for full resolution image




"Hope it helped"
Have anything in mind? Let me 
know in the comment section👇


Next Post Previous Post
No Comment
Add Comment
comment url