栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

从Python脚本获取当前目录的父目录

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

从Python脚本获取当前目录的父目录

使用os.path

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

__file__

在脚本内部使用

os.path.abspath(__file__)
来获取脚本的绝对路径,并调用
os.path.dirname
两次:

from os.path import dirname, abspathd = dirname(dirname(abspath(__file__))) # /home/kristina/desire-directory

基本上,您可以通过

os.path.dirname
根据需要调用多次来遍历目录树。例:

In [4]: from os.path import dirnameIn [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 osd = os.path.dirname(os.getcwd())

使用pathlib

您也可以使用该

pathlib
模块(在Python 3.4或更高版本中可用)。

每个

pathlib.Path
实例都具有
parent
引用父目录的
parents
属性以及该属性,该属性是路径的祖先列表。
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 Pathd = Path().resolve().parent

请注意,这

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

In [15]: str(d)Out[15]: '/home/kristina/desire-directory'


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/623806.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号