In this article, we will see how to read information from a CSV file and modify the imported data using Python. CSV package is used to read csv file information.

Guys, click me to have a look at my article describing how to backup up network devices using Python.

Tip: I’m using PyCharm community edition IDE for writing Python scripts.

Following csv file is saved at C:\SW\data.csv

The first row in the csv represent the heading

Name,Price,qty
Mango,20.3,4
Orange,23.1,6
Apple,56.3,9

Read and print CSV file

import csv

sourceFile = open("C:/SW/data.csv")
csvData = csv.reader(sourceFile)

print(list(csvData))
sourceFile.close()

Output:
[['Name', 'Price', 'qty'], ['Mango', '20.3', '4'], ['Orange', '23.1', '6'], ['Apple', '56.3', '9']]

Looping through CSV file

import csv 

sourceFile = open("C:/SW/data.csv")
csvData = csv.reader(sourceFile)
for rows in csvData:
    print(rows)

sourceFile.close()

Output: 
['Name', 'Price', 'qty']
['Mango', '20.3', '4']
['Orange', '23.1', '6']
['Apple', '56.3', '9']

Print data without heading

import csv

sourceFile = open("C:/SW/data.csv")
csvData = csv.reader(sourceFile)
for rows in csvData:
#first line represent heading
    if csvData.line_num == 1:
        continue
    print(rows)

sourceFile.close()

Output:
['Mango', '20.3', '4']
['Orange', '23.1', '6']
['Apple', '56.3', '9']

Print the items from which the price is greater than 22

import csv

sourceFile = open("C:/SW/data.csv")
csvData = csv.reader(sourceFile)

#for serial number while displaying the data 
r_count = 1

#each row item is assigned to variables name, price and quantity 
for name, price, quantity in csvData:
    if csvData.line_num == 1:
        continue
    if float(price) > 22:
        print("{}. Price of {} is {}".format(r_count, name, price))
        r_count += 1

sourceFile.close()

Output: 
Price of Orange is 23.1
Price of Apple is 56.3 

Adding column to the list of item

inport csv

sourceFile = open("C:/SW/data.csv")
csvData = csv.reader(sourceFile)

#adding extra column to the list
newlist = [x + [0] for x in csvData]
print(newlist) #Output - 1

#to get the data without heading (skipping the first row)
newlist = newlist[1:len(newlist)]
print(newlist)  #Output - 2

#below code will calculate the total amount to newely added column
# newColumn = Price * Quantity
r_count = 1
newlist1 = []
for row in newlist:
    row[3] = float(row[1]) * float(row[2])
    newlist1.append(row)

print(newlist1)  #Output - 3

sourceFile.close()

Output - 1:  
[['Name', 'Price', 'qty', 0], ['Mango', '20.3', '4', 0], ['Orange', '23.1', '6', 0], ['Apple', '56.3', '9', 0]] 

Output - 2:  
[['Mango', '20.3', '4', 0], ['Orange', '23.1', '6', 0], ['Apple', '56.3', '9', 0]]   

Output - 3:  
[['Mango', '20.3', '4', 81.2], ['Orange', '23.1', '6', 138.6], ['Apple', '56.3', '9', 506.7]]

Thank you for reading my post. Hope this is helpful to you.