问题:如何在Python中获取父目录?

有人可以告诉我如何以跨平台方式在Python中获取路径的父目录。例如

C:\Program Files ---> C:\

C:\ ---> C:\

如果该目录没有父目录,它将返回目录本身。这个问题看似简单,但我无法通过Google进行深入研究。

Could someone tell me how to get the parent directory of a path in Python in a cross platform way. E.g.

C:\Program Files ---> C:\

and

C:\ ---> C:\

If the directory doesn’t have a parent directory, it returns the directory itself. The question might seem simple but I couldn’t dig it up through Google.


回答 0

从Python 3.4更新

使用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您想要父级的路径在哪里?

Update from Python 3.4

Use the pathlib module.

from pathlib import Path
path = Path("/here/your/path/file.txt")
print(path.parent)

Old answer

Try this:

import os.path
print os.path.abspath(os.path.join(yourpath, os.pardir))

where yourpath is the path you want the parent for.


回答 1

使用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)

Using os.path.dirname:

>>> os.path.dirname(r'C:\Program Files')
'C:\\'
>>> os.path.dirname('C:\\')
'C:\\'
>>>

Caveat: os.path.dirname() gives different results depending on whether a trailing slash is included in the path. This may or may not be the semantics you want. Cf. @kender’s answer using os.path.join(yourpath, os.pardir).


回答 2

Pathlib方法(Python 3.4+)

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是什么,那么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

The Pathlib method (Python 3.4+)

from pathlib import Path
Path('C:\Program Files').parent
# Returns a Pathlib object

The traditional method

import os.path
os.path.dirname('C:\Program Files')
# Returns a string


Which method should I use?

Use the traditional method if:

  • You are worried about existing code generating errors if it were to use a Pathlib object. (Since Pathlib objects cannot be concatenated with strings.)

  • Your Python version is less than 3.4.

  • You need a string, and you received a string. Say for example you have a string representing a filepath, and you want to get the parent directory so you can put it in a JSON string. It would be kind of silly to convert to a Pathlib object and back again for that.

If none of the above apply, use Pathlib.



What is Pathlib?

If you don’t know what Pathlib is, the Pathlib module is a terrific module that makes working with files even easier for you. Most if not all of the built in Python modules that work with files will accept both Pathlib objects and strings. I’ve highlighted below a couple of examples from the Pathlib documentation that showcase some of the neat things you can do with Pathlib.

Navigating inside a directory tree:

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')

Querying path properties:

>>> q.exists()
True
>>> q.is_dir()
False

回答 3

import os
p = os.path.abspath('..')

C:\Program Files -> C:\\\

C:\ -> C:\\\

import os
p = os.path.abspath('..')

C:\Program Files —> C:\\\

C:\ —> C:\\\


回答 4

@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))     => '/'

An alternate solution of @kender

import os
os.path.dirname(os.path.normpath(yourpath))

where yourpath is the path you want the parent for.

But this solution is not perfect, since it will not handle the case where yourpath is an empty string, or a dot.

This other solution will handle more nicely this corner case:

import os
os.path.normpath(os.path.join(yourpath, os.pardir))

Here the outputs for every case that can find (Input path is relative):

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))    => '../..'

Input path is absolute (Linux path):

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))     => '/'

回答 5

os.path.split(os.path.abspath(mydir))[0]
os.path.split(os.path.abspath(mydir))[0]

回答 6

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', '..'))
os.path.abspath(os.path.join(somepath, '..'))

Observe:

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', '..'))

回答 7

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
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 "------------------------------------------------------------"

回答 8

如果你想名称是作为参数,并提供该文件的直接父文件夹的不是绝对路径到该文件中:

os.path.split(os.path.dirname(currentDir))[1]

即具有的currentDir/home/user/path/to/myfile/file.ext

上面的命令将返回:

myfile

If you want only the name of the folder that is the immediate parent of the file provided as an argument and not the absolute path to that file:

os.path.split(os.path.dirname(currentDir))[1]

i.e. with a currentDir value of /home/user/path/to/myfile/file.ext

The above command will return:

myfile


回答 9

>>> 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中尝试过

>>> import os
>>> os.path.basename(os.path.dirname(<your_path>))

For example in Ubuntu:

>>> my_path = '/home/user/documents'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'user'

For example in Windows:

>>> my_path = 'C:\WINDOWS\system32'
>>> os.path.basename(os.path.dirname(my_path))
# Output: 'WINDOWS'

Both examples tried in Python 2.7


回答 10

import os.path

os.path.abspath(os.pardir)
import os.path

os.path.abspath(os.pardir)

回答 11

假设我们有类似的目录结构

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));

Suppose we have directory structure like

1]

/home/User/P/Q/R

We want to access the path of “P” from the directory R then we can access using

ROOT = os.path.abspath(os.path.join("..", os.pardir));

2]

/home/User/P/Q/R

We want to access the path of “Q” directory from the directory R then we can access using

ROOT = os.path.abspath(os.path.join(".", os.pardir));

回答 12

只需在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"行为方式相同。

Just adding something to the Tung’s answer (you need to use rstrip('/') to be more of the safer side if you’re on a unix box).

>>> input = "../data/replies/"
>>> os.path.dirname(input.rstrip('/'))
'../data'
>>> input = "../data/replies"
>>> os.path.dirname(input.rstrip('/'))
'../data'

But, if you don’t use rstrip('/'), given your input is

>>> input = "../data/replies/"

would output,

>>> os.path.dirname(input)
'../data/replies'

which is probably not what you’re looking at as you want both "../data/replies/" and "../data/replies" to behave the same way.


回答 13

import os

dir_path = os.path.dirname(os.path.realpath(__file__))
parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))
import os

dir_path = os.path.dirname(os.path.realpath(__file__))
parent_path = os.path.abspath(os.path.join(dir_path, os.pardir))

回答 14

print os.path.abspath(os.path.join(os.getcwd(), os.path.pardir))

您可以使用它来获取py文件当前位置的父目录。

print os.path.abspath(os.path.join(os.getcwd(), os.path.pardir))

You can use this to get the parent directory of the current location of your py file.


回答 15

获取父目录路径创建新目录(名称new_dir

获取父目录路径

os.path.abspath('..')
os.pardir

例子1

import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.pardir, 'new_dir'))

例子2

import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.path.abspath('..'), 'new_dir'))

GET Parent Directory Path and make New directory (name new_dir)

Get Parent Directory Path

os.path.abspath('..')
os.pardir

Example 1

import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.pardir, 'new_dir'))

Example 2

import os
print os.makedirs(os.path.join(os.path.dirname(__file__), os.path.abspath('..'), 'new_dir'))

回答 16

os.path.abspath('D:\Dir1\Dir2\..')

>>> 'D:\Dir1'

所以有..帮助

os.path.abspath('D:\Dir1\Dir2\..')

>>> 'D:\Dir1'

So a .. helps


回答 17

import os

def parent_filedir(n):
    return parent_filedir_iter(n, os.path.dirname(__file__))

def parent_filedir_iter(n, path):
    n = int(n)
    if n <= 1:
        return path
    return parent_filedir_iter(n - 1, os.path.dirname(path))

test_dir = os.path.abspath(parent_filedir(2))
import os

def parent_filedir(n):
    return parent_filedir_iter(n, os.path.dirname(__file__))

def parent_filedir_iter(n, path):
    n = int(n)
    if n <= 1:
        return path
    return parent_filedir_iter(n - 1, os.path.dirname(path))

test_dir = os.path.abspath(parent_filedir(2))

回答 18

上面给出的答案对于上移一个或两个目录级别都是非常好的,但是如果一个人需要遍历目录树许多级别(例如5或10),它们可能会变得有些麻烦。可以通过加入中的N os.pardirs 列表来简洁地完成此操作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))

The answers given above are all perfectly fine for going up one or two directory levels, but they may get a bit cumbersome if one needs to traverse the directory tree by many levels (say, 5 or 10). This can be done concisely by joining a list of N os.pardirs in os.path.join. Example:

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))

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。