You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何用Python在macOS桌面保存KML文件?路径报错求助

解决Python在macOS桌面保存KML文件的路径问题

你遇到的核心问题是Python无法自动解析路径中的~符号——在macOS的终端里~代表当前用户的主目录,但simplekmlsave()方法并不会处理这个shell专属的缩写,所以程序找不到对应的路径。

这里有几个实用的解决方案:

方法1:用pathlib解析用户主目录(推荐,你已经导入了这个库)

pathlibPath对象自带expanduser()方法,可以自动把~替换成实际的用户主目录路径。同时我们最好提前确保保存目录存在,避免因目录缺失导致报错:

import pathlib
import simplekml

# 顺便修正你代码里的输入提示错误:纬度的提示写成了longitude
longitude = input("Enter longitude: ")
latitude = input("Enter latitude: ")

kml = simplekml.Kml()
kml.newpoint(name="Sample", coords=[(longitude, latitude)])

# 处理路径:解析~并确保上级目录存在
save_path = pathlib.Path("~/Desktop/bura/Points.kml").expanduser()
save_path.parent.mkdir(parents=True, exist_ok=True)  # 自动创建缺失的目录(包括多级目录)

kml.save(str(save_path))  # 将Path对象转为字符串传入save方法

方法2:手动替换~为用户主目录路径

如果你更习惯用字符串处理路径,可以通过os模块获取用户主目录,再替换路径中的~

import os
import simplekml

longitude = input("Enter longitude: ")
latitude = input("Enter latitude: ")

kml = simplekml.Kml()
kml.newpoint(name="Sample", coords=[(longitude, latitude)])

# 替换~为实际的用户主目录路径
save_path = "~/Desktop/bura/Points.kml".replace("~", os.environ["HOME"])
# 确保保存目录存在
os.makedirs(os.path.dirname(save_path), exist_ok=True)

kml.save(save_path)

额外小提示:

你代码里的纬度输入提示写错了,input("Enter longitude: ")应该改成input("Enter latitude: "),不然会把纬度的输入当成经度,导致坐标位置错误哦。

内容的提问来源于stack exchange,提问作者Barish Ahsen

火山引擎 最新活动