Reputation: 3
I'm totaly new to Python (and programming), so I'm stuck with some csv readings.
I have a csv file in the rows I have measurement data in the same order (in the line the first entry is the id for example 1-4). I want to get the data from the lines from line to line, I found the reader.next() function but it works a bit strange for me.
for line in reader:
print reader.next()
And I get data only from the 2. and 4. row.
['2', '112', '14.3654', '90.4555', '105.45']
['4', '114', '180.2115', '90.4555', '105.45']
The other problem is how can I take separate entries in the line? (for example: from the line id 2 the third entry 14.3654)
Appreciate any help.
Upvotes: 0
Views: 1744
Reputation: 99751
You don't need to call reader.next()
, just do this:
for line in reader:
print line
This will loop through every line in your CSV file and print it as a list:
From the documentation on next
:
Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.
What you were doing was for every line in the file, print the next line. The first time through the loop (where your for
loop is looking at line 1), it'll print the second line, and internally your position in the CSV file will be line 2. Going to the next iteration of the loop will increment your position in the CSV file to line 3. Printing reader.next()
therefore prints line 4.
To get an individual entry on each line, you can access it using subscript notation, as if it's a list:
for line in reader:
print line[0]
For a good introduction to using lists, see Dive Into Python's introduction to lists.
Upvotes: 8
Reputation: 115
You want
for line in reader:
print line
Then for individual entries in line you can have:
for entry in line:
print entry
Upvotes: 2