Pythonic 路径分裂。风格和最佳实践

Pythonic path splitting. Style, and best practice

我有一个工作模块,我想在 ROOT 目录下放置一个统一的 yaml 文件,供所有子模块使用。

我有一个 3 层深的子模块,configs.yaml 在根部。

现在我正在通过硬编码 os.path.split() 行来访问根目录,以获得尽可能多的级别,我想知道是否有更多的 pythonic,或者更好更稳健的指向目录顶部的方法.

我在 windows。 Python 3.4,使用py2exe构建。

文件夹结构如下。

还有更多

session.py 段

 if hasattr(sys, 'frozen'):
    current_directory =  os.path.split(sys.executable)[0]
else:
   current_directory = os.path.split(os.path.split(os.path.split(os.path.dirname(
    os.path.abspath("__file__")))[0])[0])[0]

editservice.py

if hasattr(sys, 'frozen'):
    basis = sys.executable
else:
    basis = os.path.dirname(os.path.abspath("__file__"))

current_directory = os.path.split(basis)[0]

是否有更一致的方法?或者也许是访问目录顶部的单行 pythonic 方式? (即使我在 windows 目录顶部不是 c:)

首先,请注意 os.path.dirname(filepath) 等同于 os.path.split(filepath)[0]

但如果您需要更上一层楼,我会使用 os.path.normpath(os.path.join(filepath, '..', '..', '..'))。恕我直言,它更具可读性。

编辑:ntpathnormpath 也将在输入路径中用 \ 替换 /,因此上面的行可以重写为 os.path.normpath(os.path.join(filepath, '../../..')),而且它是便携的。