繁体   English   中英

将值从.CSV 文件导入到 Python 脚本

[英]Importing values from .CSV file to Python script

Im working on Path Planning of Drone using GPS co ordinates given in.CSV file, How to import GPS co ordintaes from.CSV file to my Python script directly??

将位置 csv 文件具有纬度和经度值作为: locations.csv PFB 一段代码:

import csv

filename = 'D:\Python\location.csv'
n=0

with open(filename, 'r') as csvfile:
    csvreader = csv.reader(csvfile)
    fields = next(csvreader)

    for row in csvreader:
        n = n + 1
        print('location {} --> {}:{}\t{}:{}'.format(n,fields[0],row[0], fields[1],row[1]) )

Output:

location 1 --> Latitude:40.741895       Longitude:-73.989308
location 2 --> Latitude:41.741895       Longitude:-72.989308
location 3 --> Latitude:42.741895       Longitude:-71.989308
location 4 --> Latitude:43.741895       Longitude:-70.989308
location 5 --> Latitude:44.741895       Longitude:-74.989308

PFB 示例代码:

import csv

filename = 'D:\Python\location.csv'
rows = []

with open(filename, 'r') as csvfile:
    csvreader = csv.reader(csvfile)
    fields = next(csvreader)
    print(fields)

    for row in csvreader:
        print(row)
        rows.append(row)
print(rows)

output:

['Latitude', 'Longitude']
['40.741895', '-73.989308']
['41.741895', '-72.989308']
['42.741895', '-71.989308']
['43.741895', '-70.989308']
['44.741895', '-74.989308']
[['40.741895', '-73.989308'], ['41.741895', '-72.989308'], ['42.741895', '-71.989308'], ['43.741895', '-70.989308'], ['44.741895', '-74.989308']]

如果您想做的不仅仅是遍历数据,您可以查看 pandas: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.7FC35FDC7A8D226C

pd.read_csv('data.csv')  

作为进一步的扩展,还有 geopandas 可以让处理地理空间数据变得更容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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