I am having some problems getting the row values from the CSV file below
CSV
minzoom, maxzoom
0,5
5,10
10,18
My Code :
i = 0
for line in open("C:/Marine/lookup/distinct_lookup_scales.csv"):
i = i + 1
if (i > 1): #Skip header
print("Line: " + line)
#csv_row = line.split(',')
minzoom = str(line[0])
maxzoom = str(line[2])
print("Minzoom:" + minzoom)
print("Maxzoom:" + maxzoom)
readShpFile(minzoom, maxzoom)
The values returned for minzoom and maxzoom has been
0 5
5 1
1 ,
I had used line split but reverted to trying to get items from the line Not sure if that was the best approach
Vikas Periyadath
3,1961 gold badge25 silver badges35 bronze badges
asked Oct 4, 2018 at 9:56
daveb
3,5356 gold badges27 silver badges29 bronze badges
2 Answers 2
That is not how you should read the csv file. Take a look at the csv module documentation.
One example :
import csv
with open('C:/Marine/lookup/distinct_lookup_scales.csv', 'r') as csvfile:
csvreader = csv.reader(csvfile)
csvreader.next() #skip header
for row in csvreader:
minzoom = int(row[0])
maxzoom = int(row[1])
print('minzoom : {}'.format(minzoom))
print('maxzoom : {}'.format(maxzoom))
You can also use a DictReader which will use your header line to yield dictionaries.
import csv
with open('C:/Marine/lookup/distinct_lookup_scales.csv', 'r') as csvfile:
csvreader = csv.DictReader(csvfile)
for row in csvreader:
minzoom = int(row['minzoom'])
maxzoom = int(row['maxzoom'])
print('minzoom : {}'.format(minzoom))
print('maxzoom : {}'.format(maxzoom))
answered Oct 4, 2018 at 10:06
Corentin Limier
5,0861 gold badge16 silver badges24 bronze badges
Sign up to request clarification or add additional context in comments.
You can try numpy.genfromtxt, like:
import numpy as np
data = np.genfromtxt("C:/Marine/lookup/distinct_lookup_scales.csv", delimiter = ",",
skip_header = 1)
minzooms = data[:,0]
maxzooms = data[:,1]
1 Comment
daveb
Thanks Y.Wang. Not used numpy before as I am new to python but will give the approach a try. Dave
lang-py
minzoom, maxzoom = line.split(',')? Indexing doesn't work, as the zoom can be more than 10 which means you need two characters instead of one and you' may need to shift the max zoom location.