python表示当前目录_从Python脚本获取当前目录的父项

使用os.path

要获取包含脚本的目录的父目录(无论当前工作目录如何),您需要使用__file__.

from os.path import dirname, abspath

d = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory

基本上,您可以通过根据需要多次调用os.path.dirname来走向目录树.例:

In [4]: from os.path import dirname

In [5]: dirname('/home/kristina/desire-directory/scripts/script.py')

Out[5]: '/home/kristina/desire-directory/scripts'

In [6]: dirname(dirname('/home/kristina/desire-directory/scripts/script.py'))

Out[6]: '/home/kristina/desire-directory'

如果要获取当前工作目录的父目录,请使用os.getcwd:

import os

d = os.path.dirname(os.getcwd())

使用pathlib

您还可以使用pathlib模块(可用于Python 3.4或更新版本).

每个pathlib.Path实例都有父属性引用父目录,以及parent属性,它是路径的祖先列表. Path.resolve可以用来获得绝对路径.它还解析所有符号链接,但如果不是所需的行为,则可以使用Path.absolute.

Path(__ file__)和Path()分别表示脚本路径和当前工作目录,因此为了获取脚本目录的父目录(不考虑当前工作目录),您将使用

from pathlib import Path

# `path.parents[1]` is the same as `path.parent.parent`

d = Path(__file__).resolve().parents[1] # Path('/home/kristina/desire-directory')

并获取当前工作目录的父目录

from pathlib import Path

d = Path().resolve().parent

请注意,d是一个Path实例,它并不总是方便.您可以在需要时轻松将其转换为str:

In [15]: str(d)

Out[15]: '/home/kristina/desire-directory'

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值