首页 > 解决方案 > 为 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.

标签: pythonpython-3.xdirectoryoperating-system

解决方案


os.getcwd()返回工作目录,它是运行脚本的目录,而不是存储库的目录。

相反,您应该使用:

BASE_DIR = os.path.dirname(os.path.abspath(__file__))

推荐阅读