在Python中获取当前位置通常指的是获取当前工作目录,也就是Python脚本所在的目录。以下是获取当前工作目录的几种方法:
1. 使用`os`模块的`getcwd`函数:
import os
current_path = os.getcwd()
print("当前路径是:", current_path)
2. 使用`pathlib`模块的`Path.cwd`方法:
from pathlib import Path
current_directory = Path.cwd()
print("当前工作目录:", current_directory)
以上两种方法都会返回一个表示当前工作目录的字符串或路径对象。`os.getcwd()`返回一个字符串,而`Path.cwd()`返回一个`Path`对象。
如果你需要获取的是地理位置信息,那么可以使用`geopy`库,例如:
from geopy.geocoders import Nominatim
geolocator = Nominatim(user_agent="my_app")
location = geolocator.geocode("1600 Amphitheatre Parkway, Mountain View, CA")
print(location.latitude, location.longitude)
这段代码将打印出指定地址的纬度和经度坐标。
请根据你的需求选择合适的方法来获取当前位置信息