将lat长坐标数据库转换为Python中的utm数据

时间:2018-03-21 07:00:13

标签: python list csv utm

我试图将csv设置为[name | lat |一个新的csv列为[name |东方|北方|区域| - ],但它不断出现错误;

  

回溯(最近一次呼叫最后一次):文件" E:\ ACES映射   Project \ Data \ Latlong_data \ utm_request.py",第25行,in       company = eachline [0] IndexError:列表索引超出范围

我是Python的新手,但是在将地址和邮政编码的原始数据库转换为lat和long并使用非常相似的代码时没有问题,所以我不确定我做错了什么?任何帮助都会非常感谢,如果这很明显,我很抱歉。我的代码如下。

import csv
import utm

# Here enter the lat and long column numbers;

lat_col = 1
long_col = 2

# Here enter the name of the csv file for reading (r) and writing (w)

reading = 'Eng_latlong_data.csv'
writing = 'eng_utm.csv'

rawdata = open(str(reading),'r')
csv1 = csv.reader(rawdata,delimiter='|')

newdata = open(str(writing),'w')
csv2 = csv.writer(newdata,delimiter='|')

# below code will read through each line in lat long file
# then convert to utm
# and finally write as a new line with 'company name', (easting, northing, zone number, zone letter)

for eachline in csv1:
    company = eachline[0]
    print(company)
    try:
        u = utm.from_latlon(float(eachline[1]), float(eachline[2]))
        csv.writerow([company, u[0], u[1], u[2], u[3]])
    except:
        print(' ...error')

rawdata.close()
newdata.close()

1 个答案:

答案 0 :(得分:0)

这是我的固定代码,我确定可以用更少的代码完成,但如果它对任何人都有帮助,我只是在csv文件中有空行,这是使用if和else语句修复的。 if len()> 1只有当该行的长度大于1时才会运行代码,否则它不会。

    import csv
    import utm

    # Here enter the lat and long column numbers;

    lat_col = 1
    long_col = 2

    # Here enter the name of the csv file for reading (r) and writing (w)

    reading = 'SIA_latlong_data.csv'
    writing = 'SIA_utm.csv'

    rawdata = open(str(reading),'r')
    csv1 = csv.reader(rawdata,delimiter='|')

    newdata = open(str(writing),'w')
    csv2 = csv.writer(newdata,delimiter=',')

    # below code will read through each line in lat long file
    # then convert to utm
    # and finally write as a new line with 'company name', (easting, northing, zone number, zone letter)

    for eachline in csv1:
        if len(eachline) > 1:
            try:
                company = eachline[0]
                print(company)    
                u = utm.from_latlon(float(eachline[lat_col]), float(eachline[long_col]))
                csv2.writerow([str(company), str(u[0]), str(u[1]), str(u[2]), str(u[3])])
                print('written')
            except:
                print(' ...ERROR')
        else:
            print(' ...blank line')

    rawdata.close()
    newdata.close()