【问题标题】:Convert a database of lat long co-ordinates into utm data in Python在 Python 中将经纬度坐标数据库转换为 utm 数据
【发布时间】:2018-08-30 04:53:51
【问题描述】:

我正在尝试将 csv 设置为 [name |纬度 | long] 到一个新的 csv 设置为 [name |东方|北上|专区 | --],但它不断出现错误;

Traceback(最近一次调用最后一次):文件“E:\ACES Mapping Project\Data\Latlong_data\utm_request.py",第 25 行,在 company = eachline[0] IndexError: list index out of range

我是 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()

【问题讨论】:

  • 您的 CSV 文件中有空行吗?也许您可以在 company = 分配之前添加 print(eachline),以便更好地了解问题所在。
  • 是的,你是对的空行,我通过包含 if else 语句来修复它,谢谢你的帮助

标签: python list csv utm


【解决方案1】:

这是我的固定代码,我确信它可以用更少的代码完成,但如果它对任何人都有帮助,我只是在 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()

【讨论】:

    猜你喜欢
    • 2021-07-18
    • 2011-02-11
    • 1970-01-01
    • 2019-12-04
    • 2015-07-13
    • 2019-07-03
    • 2013-02-14
    • 1970-01-01
    • 2019-11-18
    相关资源
    最近更新 更多