python如何获取当前工程根目录
大家讲道理
大家讲道理 2017-04-17 17:46:09
0
6
1509

假设工程根目录为 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重名的文件

大家讲道理
大家讲道理

光阴似箭催人老,日月如移越少年。

全部回复(6)
黄舟

没有很好的办法,除非你的 Project 目录永远不移动。

在 Project 目录下加个模块获取当前文件的路径project_dir = os.path.dirname(os.path.abspath(__file__)),然后在 file.py 导进来

小葫芦

逐级往上
os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.getcwd()))))

阿神

如果你最终是在Project文件下才调动file.pyos.getcwd()的话,就会得到D:/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/了。

os.getcwd()

比如说你建立了一个这样的项目结构,如果在是在D:/Project/a/b/c/d/file.py直接调用的话,很自然就是得file.py文件所在的工作目录的路径。

如果是在D:/Project/__init__.py调用呢,那就是得到D:/Project/__init__.py所在的工作目录的路径,也就是D:/Project/了。

🎜os.getcwd()是根据调用文件所在路径的不同,得到的结果也是不同的。🎜 🎜 🎜如果你确定项目目录的名称且保证在项目目录下不会出现同名文件夹的话,可以用正则表达式。🎜
import re, os

# 测试
paths = ['d:\Project\', 'home/Python/Project/', 'c:/balabala/Python/Project/']
for path in paths:
    pj_dir = re.match('.*Project', path)
    print(pj_dir.group())
    
# 在子文件下就应该这样用
print(re.match('(.*\{sep}Project)\{sep}'.format(sep=os.sep), __file__).group(1))
小葫芦

雷雷

阿神

雷雷

小葫芦
import os

s1 = "d:/Project/a/b/c/d/file.py"
s2 = r"d:\project\a\b\c\d\file.py"

for i in [s1, s2]:
    abs_path = os.path.abspath(i).split(os.sep)
    print os.path.abspath(abs_path[0] + os.sep + abs_path[1])

适用于""和"/"的目录分隔符

热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!