python - 为 python 文件设置一致的主目录
问题描述
我正在编写一个 python 脚本,它依赖于其存储库中的目录。我想学习一种方法来创建一个始终位于存储库目录中心的主目录。对于希望在他或她的服务器上克隆此存储库的任何人来说,这应该是通用的。
当我在存储库目录中运行脚本时,该脚本可以很好地访问其依赖目录。如果我要在存储库目录之外运行脚本,则会引发FileNotFoundError异常。规避此问题的最佳方法是什么?
# if I run this in the repo directory, it works just fine
import os.path
base_dir = os.getcwd()
csv_dir = f'{base_dir}/CSV'
# however, if I run this in a directory outside of the repository (e.g.
# $ python dir1/dir2/file.py ), a FileNotFoundError is thrown.
解决方案
os.getcwd()
返回工作目录,它是运行脚本的目录,而不是存储库的目录。
相反,您应该使用:
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
推荐阅读
- javascript - 如何在jquery属性值中设置变量
- php - 通过带有 href 的 id 链接获取价值
- aem - 是否可以在不使用 JavaScript 的情况下检查要在 AEM 网站上突出显示的特定文本?
- ios - 将通过 AlamoFire 下载的 MPEG 音频文件转换为 mp3 文件
- javascript - 不工作:Highcharts bar plotOptions series className
- amazon-web-services - 如何通过角色链接来限制 IAM 角色以获得比其本身所允许的更高的权限?
- graph-theory - 在无向图中找到所有可能的简单路径是 NP hard/ NP complete
- fortran - Fortran IIFIX 未知符号
- c# - 如何在“Unity”中使用 Firebase 在某些日子重置游戏分数
- sql - 避免循环导致的数据库往返