问题描述
作为Python的初学者,我正在处理一项任务.该任务正在开发一个程序,该程序通过虚拟端口读取NMEA日志文件,并且:
- 仅打印"GPGGA"行
- 从这些"GPGGA"行打印坐标(纬度,经度)
- 在CSV文件中提取这些坐标
- 在KML文件中提取这些坐标
遵循我的代码:
导入序列从pynmea导入nmea导入csvser = serial.Serial('COM4')ser.baudrate = 4800f =打开('coord_list.csv','w +')打印(等待数据")而True:尝试:消息= ser.readline().decode()消息= message.strip()如果消息中有"$ GPGGA":打印(留言)gpgga = nmea.GPGGA()gpgga.parse(消息)lat = float(gpgga.latitude)lon =浮点数(gpgga.longitude)print("Lat%f Long%f"%(lat,lon))为我在消息中:coord_list = []坐标= [gpgga.latitude,gpgga.longitude]coord_list.append(coord)f.write(coord_list)f.close()除了KeyboardInterrupt:增加ser.close()
对于前两个项目符号,示例输出如下:
等待数据$ GPGGA,170609.941,5335.6665,N,01021.2637,E,1,09,01.1,35.9,M,40.2,M ,, * 58纬度5335.666500长1021.263700$ GPGGA,170610.941,5335.6665,N,01021.2637,W,1,09,01.1,36.0,M,40.2,M,* 5A
使用此代码,我得到了一个错误:
f.write(coord_list)TypeError:write()参数必须为str,而不是list
我无法将坐标保存在CSV文件下.我不知道如何编写正确的代码来解决它.无论我尝试什么,我都会遇到其他错误或什么也没有.
问题出在您的错误提示上, write
仅采用字符串.
csv格式通常以逗号分隔.
所以你可以这样:
f.write("{},{} \ n" .format(gpgga.latitude,gpgga.longitude))
也可以在循环中关闭文件,但不要打开它.因此它不会在第一个循环后写入.
As a beginner in Python I am dealing with a task. The task is developing a program that reads the NMEA log files via a virtual port and:
- printing only "GPGGA" lines
- printing coordinates (lat,lon) from these "GPGGA" lines
- extracting these coordinates in a CSV file
- extracting these coordinates in a KML file
My code is followed:
import serial
from pynmea import nmea
import csv
ser=serial.Serial('COM4')
ser.baudrate=4800
f = open('coord_list.csv', 'w+')
print('Waiting for data')
while True:
try:
message = ser.readline().decode()
message = message.strip()
if '$GPGGA' in message:
print(message)
gpgga = nmea.GPGGA()
gpgga.parse(message)
lat = float(gpgga.latitude)
lon = float(gpgga.longitude)
print("Lat %f Long %f" % (lat, lon))
for i in message:
coord_list = []
coord = [gpgga.latitude,gpgga.longitude]
coord_list.append(coord)
f.write(coord_list)
f.close()
except KeyboardInterrupt:
raise
ser.close()
For the first two bullets a sample output is like:
Waiting for data
$GPGGA,170609.941,5335.6665,N,01021.2637,E,1,09,01.1,35.9,M,40.2,M,,*58
Lat 5335.666500 Long 1021.263700
$GPGGA,170610.941,5335.6665,N,01021.2637,W,1,09,01.1,36.0,M,40.2,M,,*5A
With this code I got an error:
f.write(coord_list)
TypeError: write() argument must be str, not list
I get stuck on saving coordinates under a CSV file. I couldn't figure out how to write a correct code to solve it. Whatever I tried I got another errors or nothing.
The problem is as your error says, that write
takes string only.
csv format is usually comma seperated.
So you could do like this :
f.write("{},{}\n".format(gpgga.latitude, gpgga.longitude))
Also you close the file in the loop, but dont open it. So it won't write after first loop.
这篇关于从NMEA日志文件中提取的坐标保存在CSV文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!