活到老学到老之python os模块常用方法
从完整路径里 去掉最后的文件名,只保留目录部分
例如,local_path 是 xxx/xxx/xxx/test_app.apk,将这个路径后面的部分test_app.apk去掉
- os.path.dirname(跨平台性比较好)
import oslocal_path = "xxx/xxx/xxx/test_app.apk"
dir_path = os.path.dirname(local_path)
print(dir_path) # xxx/xxx/xxx
- pathlib
from pathlib import Pathlocal_path = Path("xxx/xxx/xxx/test_app.apk")
dir_path = local_path.parent
print(dir_path) # xxx/xxx/xxx
将目录路径 dir_path 和 文件名 拼接起来,生成一个新的路径
os.path.join
apk_dir_path = os.path.join(dir_path, "test_app.apk")
得到结果是:
xxx/xxx/xxx/test_app.apk
- os.path.join 会自动处理路径分隔符 /(在 Windows 下会变成 \,在 Linux/macOS 下是 /)。
- 它比手动拼接字符串(dir_path + “/test_app.apk”)更安全、跨平台。
获取完整绝对路径
os.path.abspath(file)
import os# 当前脚本所在目录
BASE_DIR = os.path.dirname(os.path.abspath(__file__))# 拼接成绝对路径
bundletool_path = os.path.abspath(os.path.join(BASE_DIR, "..", "..", "bundletool.jar"))
jks_path = os.path.abspath(os.path.join(BASE_DIR, "..", "..", "debug.jks"))print("Bundletool Path:", bundletool_path)
print("JKS Path:", jks_path)
- file 当前 Python 文件路径。
- os.path.abspath(file) 得到完整绝对路径。
- os.path.dirname(…) 取出脚本所在目录。
- os.path.join(BASE_DIR, “…”, “…”, “xxx”) 从脚本所在目录往上两层,拼接目标文件。
- os.path.abspath(…) 把相对路径再转成系统标准的绝对路径。
执行结果:
假如脚本路径是:
/Users/test/project/tools/scripts/my_script.py
bundletool_path 就会变成:
/Users/test/project/bundletool.jar
jks_path 就会变成:
/Users/test/project/debug.jks