https://comate.baidu.com/zh/page/a6emajt9jkp
方法对比与实现
使用os.getcwd()获取当前工作目录
1
2
3
4
5
| import os
# 获取当前工作目录
current_dir = os.getcwd()
print("当前工作目录:", current_dir)
|
说明:返回进程启动时的工作目录,可能与脚本所在目录不同。
使用os.path.abspath(__file__)获取脚本绝对路径
1
2
3
4
5
| import os
# 获取当前脚本的绝对路径
script_path = os.path.abspath(__file__)
print("脚本绝对路径:", script_path)
|
说明:__file__是当前脚本的文件名,交互式环境中不可用。
使用os.path.dirname获取脚本所在目录
1
2
3
4
5
| import os
# 获取脚本所在目录
script_dir = os.path.dirname(os.path.abspath(__file__))
print("脚本所在目录:", script_dir)
|
说明:常用于定位脚本同级目录下的资源文件。
使用pathlib.Path.cwd()获取工作目录(推荐)
1
2
3
4
5
| from pathlib import Path
# 获取当前工作目录(Path对象)
path_dir = Path.cwd()
print("工作目录(Path):", path_dir)
|
说明:面向对象的方式,更符合现代Python编程风格。
使用pathlib.Path(__file__)获取脚本路径
1
2
3
4
5
6
| from pathlib import Path
# 获取脚本路径和父目录
current_file = Path(__file__).resolve()
print("脚本绝对路径:", current_file)
print("脚本父目录:", current_file.parent)
|
说明:resolve()可解析符号链接,parent属性直接获取父目录。
方法对比表
1
2
3
4
5
6
7
| 方法 适用场景 返回值类型 备注
os.getcwd() 获取工作目录 字符串 交互式环境可用
os.path.abspath(__file__) 获取脚本路径 字符串 脚本专用
os.path.dirname() 获取父目录 字符串 需配合abspath
Path.cwd() 获取工作目录 Path对象 推荐现代用法
Path(__file__).resolve() 获取脚本路径 Path对象 支持符号链接解析
|