清理将文件路径拆分为它的组件

时间:2016-05-18 18:48:06

标签: python

我正在尝试以pythonic方式将路径转换为其组件。

示例:

path = /drive/dir/anotherdir/finaldir/

方法

splitted = path.split(os.path.sep)
>>> ['', 'drive', 'dir', 'anotherdir', 'finaldir', '']

通缉输出:

>>> ['drive', 'dir', 'anotherdir', 'finaldir']

是否有更简洁的方式,以便没有空字符串条目?切片很容易解决,但它只会增加不必要的噪音。我查看了 os.path 模块,唯一的拆分器是:

os.path.split(path)
os.path.splitdrive(path)
os.path.splitext(path)
os.path.splitunc(path)

P.S。:我不是在寻找一个解决方案我只是想确定是否有一个解决方案我没有考虑到帐户。

2 个答案:

答案 0 :(得分:2)

试试这个吗?

path.strip('/').split('/')

答案 1 :(得分:1)

考虑到path可能带来的值,Mark Ransom所说的通缉输出无效。在谈论路径时,操作系统有一些关于如何将路径字符串解析为文件或目录的约定。

考虑以下代码:

def toComponents(path):
    return path.split('/')


def fromComponents(components):
    return '/'.join(components)

# specialToComponents takes a path and returns
# the components relative to the / folder or
# if the path is relative, it returns the components
# Use at your own risk.
def specialToComponents(path):
    return path.strip('/').split('/')

假设您有两条路径:

  • path = /drive/dir/anotherdir/finaldir/这是一个绝对路径,它告诉读者和操作系统文件位于/文件夹内,path文件夹内等等,直到{{ 1}}
  • finaldir/这是一条相对路径。它通常意味着相对于程序的当前目录。它说转到当前目录,然后转到path = drive/dir/anotherdir/finaldir/然后转到drive,依此类推,直到dir

你要做的是将绝对路径作为相对路径读取,将相对路径读取为相对路径,这很好,只要当有人试图在绝对路径上运行代码时,它不会给你带来麻烦。