JabbaJava
JabbaJava

Reputation: 325

Python Nested For Loop CSV File

This code only iterates through the number of rows once I would like to iterate through all the rows for the number of columns in the data I'm confused as to why it isn't iterating through the rows 7 times.

import  csv
from    mpl_toolkits.mplot3d import axes3d
import  matplotlib.pyplot   as  plt
import  numpy   as  np

sensorData      =   []
longitudinal    =   []
transverse      =   []

n=0
with open('test3.csv') as csvfile:
     readCsv = csv.reader(csvfile, delimiter =',')
     for x in range(0,7):    #problem HERE
         for row in readCsv:
             n+=1
             sensorData.append(float(row[x]))

             longitudinal.append(n)

             transverse.append(x)

Upvotes: 2

Views: 1736

Answers (3)

lafferc
lafferc

Reputation: 2769

Your code has a outer loop that will loop 7 times, and the inner loop will loop over each row. You need to swap the inner and outer loops.

For each row loop over each column

with open('test3.csv') as csvfile:
     readCsv = csv.reader(csvfile, delimiter =',')
     for row in readCsv:
         for x in range(0,7):
             n+=1
             sensorData.append(float(row[x]))

Upvotes: 1

Robbie Jones
Robbie Jones

Reputation: 391

Similar question here: Reading from CSVs in Python repeatedly?

After you loop through the file, you need to reset the read position of csvfile.

    csvfile.seek(0)

Upvotes: 1

John Gordon
John Gordon

Reputation: 33335

Once you read all the rows in the file, the file data is exhausted and there's nothing left to read, so your for row in readCsv: loop immediately terminates.

If you want to reset the file and read it all over again, you'll need to close the file and open it again.

Upvotes: 0

Related Questions