有人可以告诉我如何以跨平台方式在Python中获取路径的父目录。例如
C:\Program Files ---> C:\
和
C:\ ---> C:\
如果该目录没有父目录,它将返回目录本身。这个问题看似简单,但我无法通过Google进行深入研究。
有人可以告诉我如何以跨平台方式在Python中获取路径的父目录。例如
C:\Program Files ---> C:\
和
C:\ ---> C:\
如果该目录没有父目录,它将返回目录本身。这个问题看似简单,但我无法通过Google进行深入研究。
Answers:
使用pathlib
模块。
from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent)
尝试这个:
import os.path
print os.path.abspath(os.path.join(yourpath, os.pardir))
yourpath
您想要父级的路径在哪里?
os.pardir
,不是os.path.pardir
。
os.pardir
和os.path.pardir
实际上都是正确的(它们是相同的)。
os.path.dirname
是,根据路径中是否包含斜杠,会给出不同的结果。如果您想要可靠的结果,则需要使用os.path.join
上面答案中的方法。
使用os.path.dirname
:
>>> os.path.dirname(r'C:\Program Files')
'C:\\'
>>> os.path.dirname('C:\\')
'C:\\'
>>>
警告:os.path.dirname()
根据路径中是否包含斜杠给出不同的结果。这可能是您想要的语义,也可能不是。cf. @kender使用的答案os.path.join(yourpath, os.pardir)
。
os.path.dirname(r'C:\Program Files')
什么?Python只是为您提供文件“ Program Files”所在的目录。而且,它甚至不必存在,请看:os.path.dirname(r'c:\i\like\to\eat\pie')
输出'c:\\i\\like\\to\\eat'
from pathlib import Path
Path('C:\Program Files').parent
# Returns a Pathlib object
import os.path
os.path.dirname('C:\Program Files')
# Returns a string
在以下情况下,请使用传统方法:
如果使用Pathlib对象,您会担心现有代码会生成错误。(由于Pathlib对象不能与字符串连接。)
您的Python版本低于3.4。
您需要一个字符串,并且您收到了一个字符串。假设您有一个表示文件路径的字符串,并且想要获取父目录,以便可以将其放入JSON字符串中。转换为Pathlib对象并为此再次返回是一种愚蠢的做法。
如果以上都不适用,请使用Pathlib。
如果您不知道Pathlib是什么,那么Pathlib模块是一个了不起的模块,它使您更轻松地处理文件。大多数(如果不是全部)与文件一起使用的内置Python模块将接受Pathlib对象和字符串。我在下面重点介绍了Pathlib文档中的几个示例,这些示例展示了您可以使用Pathlib进行的一些巧妙操作。
在目录树中导航:
>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')
查询路径属性:
>>> q.exists()
True
>>> q.is_dir()
False
pip install pathlib2
使用backport。
os.sep
!
import os
p = os.path.abspath('..')
C:\Program Files
-> C:\\\
C:\
-> C:\\\
os.path.abspath(r'E:\O3M_Tests_Embedded\branches\sw_test_level_gp\test_scripts\..\..')
结果:E:\\O3M_Tests_Embedded\\branches
/
。
@kender的替代解决方案
import os
os.path.dirname(os.path.normpath(yourpath))
yourpath
您想要父级的路径在哪里?
但是这种解决方案并不完美,因为它不能处理yourpath
空字符串或点的情况。
这个其他解决方案可以更好地处理这种极端情况:
import os
os.path.normpath(os.path.join(yourpath, os.pardir))
在这里可以找到的每种情况的输出(输入路径是相对的):
os.path.dirname(os.path.normpath('a/b/')) => 'a'
os.path.normpath(os.path.join('a/b/', os.pardir)) => 'a'
os.path.dirname(os.path.normpath('a/b')) => 'a'
os.path.normpath(os.path.join('a/b', os.pardir)) => 'a'
os.path.dirname(os.path.normpath('a/')) => ''
os.path.normpath(os.path.join('a/', os.pardir)) => '.'
os.path.dirname(os.path.normpath('a')) => ''
os.path.normpath(os.path.join('a', os.pardir)) => '.'
os.path.dirname(os.path.normpath('.')) => ''
os.path.normpath(os.path.join('.', os.pardir)) => '..'
os.path.dirname(os.path.normpath('')) => ''
os.path.normpath(os.path.join('', os.pardir)) => '..'
os.path.dirname(os.path.normpath('..')) => ''
os.path.normpath(os.path.join('..', os.pardir)) => '../..'
输入路径是绝对路径(Linux路径):
os.path.dirname(os.path.normpath('/a/b')) => '/a'
os.path.normpath(os.path.join('/a/b', os.pardir)) => '/a'
os.path.dirname(os.path.normpath('/a')) => '/'
os.path.normpath(os.path.join('/a', os.pardir)) => '/'
os.path.dirname(os.path.normpath('/')) => '/'
os.path.normpath(os.path.join('/', os.pardir)) => '/'
os.path.split(os.path.abspath(mydir))[0]
os.path.split(os.path.abspath("this/is/a/dir/"))[0]
返回'/home/daniel/this/is/a'
预期。我目前没有正在运行的Windows框可供检查。在哪种设置上,您观察到了报告的行为?
parentdir = os.path.split(os.path.apspath(dir[:-1]))[0]
。我敢肯定,这是有效的,因为如果结尾处有斜杠,则将其删除;如果没有斜杠,则由于前面的斜杠,它仍然可以工作(即使路径的最后部分只有一个字符长)。当然,这是假定路径是正确的,而不是说类似的东西/a//b/c///d////
(在Unix中,这仍然有效),在大多数情况下,它们是(适当的),尤其是当您执行类似的东西os.path.abspath
或任何其他os.path
功能时。
os.path.split("a/b//c/d///")
,则此命令不起作用。所有这些都在linux中有效。我只是想出了这一点,它可能是有用的,但:。(这实际上是搜索最后一个非斜杠,并获取到该char的路径的子字符串。)我使用过,然后运行上述语句并得到了。cd //////dev////// is equivalent to
cd /dev
os.path.split(path[:tuple(ind for ind, char in enumerate(path) if char != "/" and char != "\\")[-1]])[0]
path = "/a//b///c///d////"
'/a//b///c'
os.path.abspath(os.path.join(somepath, '..'))
观察:
import posixpath
import ntpath
print ntpath.abspath(ntpath.join('C:\\', '..'))
print ntpath.abspath(ntpath.join('C:\\foo', '..'))
print posixpath.abspath(posixpath.join('/', '..'))
print posixpath.abspath(posixpath.join('/home', '..'))
import os
print"------------------------------------------------------------"
SITE_ROOT = os.path.dirname(os.path.realpath(__file__))
print("example 1: "+SITE_ROOT)
PARENT_ROOT=os.path.abspath(os.path.join(SITE_ROOT, os.pardir))
print("example 2: "+PARENT_ROOT)
GRANDPAPA_ROOT=os.path.abspath(os.path.join(PARENT_ROOT, os.pardir))
print("example 3: "+GRANDPAPA_ROOT)
print "------------------------------------------------------------"
>>> import os
>>> os.path.basename(os.path.dirname(<your_path>))
例如在Ubuntu中:
>>> my_path = '/home/user/documents'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'user'
例如在Windows中:
>>> my_path = 'C:\WINDOWS\system32'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'WINDOWS'
两个示例都在Python 2.7中尝试过
假设我们有类似的目录结构
1]
/home/User/P/Q/R
我们要从目录R访问“ P”的路径,然后可以使用
ROOT = os.path.abspath(os.path.join("..", os.pardir));
2]
/home/User/P/Q/R
我们要从目录R访问“ Q”目录的路径,然后可以使用
ROOT = os.path.abspath(os.path.join(".", os.pardir));
只需在Tung的答案中添加一些内容即可(rstrip('/')
如果您使用的是unix盒,则需要更加安全一些)。
>>> input = "../data/replies/"
>>> os.path.dirname(input.rstrip('/'))
'../data'
>>> input = "../data/replies"
>>> os.path.dirname(input.rstrip('/'))
'../data'
但是,如果您不使用rstrip('/')
,则输入为
>>> input = "../data/replies/"
会输出
>>> os.path.dirname(input)
'../data/replies'
这可能不是您想要的,"../data/replies/"
并且"../data/replies"
行为方式相同。
import os
dir_path = os.path.dirname(os.path.realpath(__file__))
parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))
获取父目录路径并创建新目录(名称new_dir
)
os.path.abspath('..')
os.pardir
import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.pardir, 'new_dir'))
import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.path.abspath('..'), 'new_dir'))
上面给出的答案对于上移一个或两个目录级别都是非常好的,但是如果一个人需要遍历目录树许多级别(例如5或10),它们可能会变得有些麻烦。可以通过加入中的N
os.pardir
s 列表来简洁地完成此操作os.path.join
。例:
import os
# Create list of ".." times 5
upup = [os.pardir]*5
# Extract list as arguments of join()
go_upup = os.path.join(*upup)
# Get abspath for current file
up_dir = os.path.abspath(os.path.join(__file__, go_upup))
os.path.dirname
是此功能,例如a+=5-4
比a+=1
。该问题仅请求父目录,而不是是否存在或假设符号链接妨碍了真正的父目录。