dpalm dpalm - 3 months ago 10
Python Question

printing from csv.reader

This should be an easy one, but I'm having a bit of a brain fart. the CSV maintains a list of four latitude and longitude pairs. Based on the code, if I print row[0] it prints just the latitudes and if I print row[1] it prints the longitudes. How to I format the code to print a specific lat/lon pair instead? Say.. The second lat/lon pair in the CSV.

import csv

with open('120101.KAP.csv','rb') as csvfile:
reader = csv.reader(csvfile)
for row in reader:
print row[0]

Answer

Looping over reader gives you each row. If you wanted to get the second row, use the next() function instead, ignore one and get the second:

reader = csv.reader(csvfile)
next(reader)  # ignore
row = next(reader)  # second row
print row           # print the second row.

You can generalise this by using the itertools.islice() object to do the skipping for you:

from itertools import islice

reader = csv.reader(csvfile)
row = next(islice(reader, rownumber))  # skip to index rownumber, read that
print row

Take into account that counting starts at 0, so "second row" is rownumber = 1.

Or you could just read all rows into a list and index into that:

reader = csv.reader(csvfile)
rows = list(reader)
print rows[1]  # print the second row
print rows[3]  # print the fourth row

Only do this (loading everything into a list) if there are a limited number of rows. Iteration over the reader only produces one row at a time and uses a file buffer for efficient reading, limiting how much memory is used; you could process gigantic CSV files this way.