简体   繁体   中英

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

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

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM