In this post I will explain you how to read CSV files with python. To store tabular data we use this simple type of file format. The data can be imported from and exported to CSV files using programs.

The following python program will help you to read CSV file and using the data it will plot a line. With comments, I hope you can understand the program. Download the divi.csv from this link.

 

import numpy as np
import matplotlib.pyplot as plt

readFile = np.loadtxt(“divi.csv”, delimiter=’,’)

LineNum = 0 # Lets take the line number of CSV file as LineNum

”’ Now lets start two arrays.
One is to hold row total and other is to hold line numbers”’

SubTot = []
Counter = []

while LineNum < len(readFile): #Start the loop until it reads the all lines of the file

Counter.append(LineNum)

RowTotal = sum(readFile[LineNum,:])   # Lets take the total for each row

#If you need running sum of columns use sum(readFile[:ColumnNum])

LineNum +=1 # Next line

SubTot.append(RowTotal) # Append each row total to the array

plt.plot(SubTot, label=”Sub Total”) # Lets plot the values of SubTot

plt.legend()

plt.show()

Work with CSV files

Leave a Reply

Your email address will not be published. Required fields are marked *