假设工程根目录为 d:/Project/
然后在 d:/Project/a/b/c/d/file.py 里使用 os.getcwd() 方法获取的是
d:/Project/a/b/c/d
现在我想获取 d:/Project 怎么做?
------------------------------------分割线---------------------------------
谢谢大家的热情回答,都怪我没有将问题说清楚,我的意思是获取当前工程的根目录,而获取根目录的函数可能在任何目录下
根目录既可能是 d:/Project/
也可能是 d:/Python/Project/
也可能是 d:/balabala/Python/Project/
因此逐级往上也是不可能找到的,我目前的方法是在根目录下放一个文件 file
然后这样:
def getSeparator():
if 'Windows' in platform.system():
separator = '\\'
else:
separator = '/'
return separator
def findPath(file):
o_path = os.getcwd()
separator = getSeparator()
str = o_path
str = str.split(separator)
while len(str) > 0:
spath = separator.join(str)+separator+file
leng = len(str)
if os.path.exists(spath):
return spath
str.remove(str[leng-1])
但是这样也有一个问题,就是必须保证任何目录下不能有和根目录下file重名的文件
There is no good way unless your Project directory is never moved.
Add a module in the Project directory to get the path of the current file
project_dir = os.path.dirname(os.path.abspath(__file__))
, and then import it in file.pyGo up step by step
os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.getcwd()))))
If you finally mobilize file.py's
os.getcwd()
under the Project file, you will get the result ofD:/Project
.os.getcwd()
的话,就会得到D:/Project
这个结果。比如说你建立了一个这样的项目结构,如果在是在
D:/Project/a/b/c/d/file.py
直接调用的话,很自然就是得file.py
文件所在的工作目录的路径。如果是在
D:/Project/__init__.py
调用呢,那就是得到D:/Project/__init__.py
所在的工作目录的路径,也就是D:/Project/
了。
For example, if you create a project structure like this, if you call it directly inos.getcwd()
D:/Project/a/b/c/d/file.py
, it will naturally befile.py
The path to the working directory where the file is located.If it is called from
🎜D:/Project/__init__.py
, then the path to the working directory whereD:/Project/__init__.py
is located is obtained, that is, D:/Project/.os.getcwd()
The results obtained are different depending on the path of the calling file. 🎜 🎜 🎜If you are sure of the name of the project directory and ensure that no folder with the same name will appear in the project directory, you can use regular expressions. 🎜Directory separator for "" and "/"