文章内容

2024/2/2 0:02:39,作 者: 黄兵

Python 获取父目录路径

如果我们在 Python 中需要获取父目录路径,可以使用 os.path.abspathos.path.dirname 函数来构建新的路径。

以下是代码示例:

import os

# 获取当前文件所在目录的上级目录
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))

# 构建 .env 文件的路径
dotenv_path = os.path.join(parent_dir, '.env')

# 确保路径存在
if os.path.exists(dotenv_path):
    # 执行您的操作,比如加载环境变量等
    pass
else:
    print(f"Error: {dotenv_path} not found.")

这里使用了 os.path.dirname(__file__) 获取当前脚本文件所在的目录,然后通过 os.path.abspath 获取其绝对路径。

接着使用 os.path.join 构建了上级目录的路径,并在此基础上构建了 .env 文件的路径。

最后,通过 os.path.exists 检查文件是否存在,确保路径有效性。

请注意,这里使用了 __file__ 来获取当前脚本文件的路径。如果您在交互式环境中执行,可能需要适当调整。


其它相关推荐:

1、Python List tuple理解

2、python 解析linuxtraceroute结果

3、Ubuntu 运行python Killed

4、在Python 3中Concurrent.futures 与 Multiprocessing 的区别

5、python 多线程长时间运行程序

分享到:

发表评论

评论列表