如何在Python中获得父目录?

时间:2021-01-27 07:09:15

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

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

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.

如果目录没有父目录,则返回目录本身。这个问题看起来很简单,但我无法通过谷歌挖掘出来。

17 个解决方案

#1


277  

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.

你的路径是你想要父母的路径。

#2


240  

Using os.path.dirname:

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

注意:os.path.dirname()给出了不同的结果,这取决于在路径中是否包含了拖尾斜杠。这可能是您想要的语义。Cf. @kender使用os.path的答案。加入(yourpath os.pardir)。

#3


62  

In Python 3.4+

在Python 3.4 +

from pathlib import Path
Path('C:\Program Files').parent

doc page

文档页面


Additional Info

额外的信息

The new pathlib library brings together and simplifies using paths and common file operations. Here are some examples from the docs.

新的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

#4


22  

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

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

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

C:\ ---> C:\\\

C:\ - - - > C:\ \ \

#5


14  

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

#6


14  

An alternate solution of @kender

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

输入路径是绝对的(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))     => '/'

#7


12  

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

#8


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

#9


3  

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]

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

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

例如,使用/home/user/path/to/myfile/file.ext的currentDir值。

The above command will return:

上述命令将返回:

myfile

myfile

#10


2  

import os.path

os.path.abspath(os.pardir)

#11


2  

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

如果你在unix上,你需要使用rstrip('/')来增加更安全的一面。

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

但是,如果你不使用rstrip('/'),你的输入是。

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

这可能并不是你想要的那样。/数据/回复/”和“. ./数据/回复“以同样的方式表现。

#12


1  

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.

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

#13


0  

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

获取父目录路径并创建新目录(名称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'))

#14


0  

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

>>> 'D:\Dir1'

So a .. helps

所以. .帮助

#15


0  

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

#16


0  

import os

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

#17


0  

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

For example in Ubuntu:

例如在Ubuntu中:

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

For example in Windows:

例如在Windows中:

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

Both examples tried in Python 2.7

这两个示例都使用了Python 2.7。

#1


277  

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.

你的路径是你想要父母的路径。

#2


240  

Using os.path.dirname:

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

注意:os.path.dirname()给出了不同的结果,这取决于在路径中是否包含了拖尾斜杠。这可能是您想要的语义。Cf. @kender使用os.path的答案。加入(yourpath os.pardir)。

#3


62  

In Python 3.4+

在Python 3.4 +

from pathlib import Path
Path('C:\Program Files').parent

doc page

文档页面


Additional Info

额外的信息

The new pathlib library brings together and simplifies using paths and common file operations. Here are some examples from the docs.

新的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

#4


22  

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

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

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

C:\ ---> C:\\\

C:\ - - - > C:\ \ \

#5


14  

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

#6


14  

An alternate solution of @kender

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

输入路径是绝对的(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))     => '/'

#7


12  

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

#8


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

#9


3  

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]

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

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

例如,使用/home/user/path/to/myfile/file.ext的currentDir值。

The above command will return:

上述命令将返回:

myfile

myfile

#10


2  

import os.path

os.path.abspath(os.pardir)

#11


2  

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

如果你在unix上,你需要使用rstrip('/')来增加更安全的一面。

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

但是,如果你不使用rstrip('/'),你的输入是。

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

这可能并不是你想要的那样。/数据/回复/”和“. ./数据/回复“以同样的方式表现。

#12


1  

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.

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

#13


0  

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

获取父目录路径并创建新目录(名称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'))

#14


0  

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

>>> 'D:\Dir1'

So a .. helps

所以. .帮助

#15


0  

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

#16


0  

import os

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

#17


0  

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

For example in Ubuntu:

例如在Ubuntu中:

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

For example in Windows:

例如在Windows中:

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

Both examples tried in Python 2.7

这两个示例都使用了Python 2.7。