Search code examples
pythoncsvstring-parsing

Reading values for CSV file using Python


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


Solution

  • 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))