4

有没有办法从给定的目录中获得高于或低于目录的一级?例如,在函数中输入了“/a/b/c/”目录。

所以函数会返回:

lvl_down = '/a/b/'
lvl_up = '/a/b/c/d/'

我认为你可以使用're'模块(至少在目录下一级)来做到这一点,但也许没有正则表达式有更简单和更好的方法吗?

4

3 回答 3

9

我不知道函数应该如何知道你想进入目录d

#!/usr/bin/python
import os.path

def lvl_down(path):
    return os.path.split(path)[0]

def lvl_up(path, up_dir):
    return os.path.join(path, up_dir)

print(lvl_down('a/b/c'))   # prints a/b
print(lvl_up('a/b/c','d')) # prints a/b/c/d

注意:之前有另一种解决方案,但 os.path 是一个更好的解决方案。

于 2012-11-02T11:50:53.463 回答
2

操作路径的方法可以在模块osos.path.

os.path.join - 智能地加入一个或多个路径组件。

os.path.split - 将路径名路径拆分为一对,(head, tail)其中tail是最后一个路径名组件,而head是导致该路径的所有内容。

os.path.isdir -如果 path 是现有目录,则返回True 。

os.listdir - 返回一个列表,其中包含由path给出的目录中的条目名称。

def parentDir(dir):
    return os.path.split(dir)[0]

def childDirs(dir):
    possibleChildren = [os.path.join(dir, file) for file in os.listdir(dir)]
    return [file for file in possibleChildren if os.path.isdir(file)]
于 2012-11-02T12:07:43.183 回答
1

首先,如果给定的路径以斜线结尾,则应始终使用切片将其删除。话虽如此,以下是如何获取路径的父目录:

>>> import os.path
>>> p = '/usr/local'
>>> os.path.dirname(p)
'/usr'

要下去,只需将名称附加到变量中,如下所示:

>>> head = '/usr/local'
>>> rest = 'include'
>>> os.path.join(head, rest)
'/usr/local/include'
于 2012-11-02T12:17:45.953 回答