从下面的CSV文件获取行值时遇到一些问题
CSV
minzoom, maxzoom
0,5
5,10
10,18
我的代码:
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)
为 minzoom 和 maxzoom 返回的值已经
0 5
5 1
1 ,
我曾经使用过行拆分,但是恢复为尝试从行中获取项目 不确定这是否是最好的方法
答案 0 :(得分:3)
那不是您应该读取csv文件的方式。 看看csv module documentation。
一个例子:
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))
您还可以使用DictReader,它将使用标题行生成字典。
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))
答案 1 :(得分:0)
您可以尝试使用numpy.genfromtxt,例如:
import numpy as np
data = np.genfromtxt("C:/Marine/lookup/distinct_lookup_scales.csv", delimiter = ",",
skip_header = 1)
minzooms = data[:,0]
maxzooms = data[:,1]