Python:更改路径的部分(单个目录名称)

时间:2014-03-16 22:49:21

标签: python path directory

在路径中更改单个目录名称(仅第一次出现)的最佳方法是什么?

示例:

source_path = "/path/to/a/directory/or/file.txt"
target_path = "/path/to/different/directory/or/file.txt"

在这种情况下,指令将是:“将名称'a'的第一个目录替换为名称为'different'的目录”

我可以想到一些方法,我首先在单个部分中拆分路径,然后找到第一个“a”,替换它并再次加入它。但我想知道是否有更优雅的方式来解决这个问题。也许是一个内置的python函数。

4 个答案:

答案 0 :(得分:2)

有一个名为os.path.split的函数可以将一条路径分成最后一部分并且所有引导到它的路径但是这是你最接近的路径。因此,我们可以做的最优雅的事情是创建一个连续调用它的函数:

import os, sys 
def splitall(path): 
    allparts = [] 
    while 1: 
        parts = os.path.split(path) 
        if parts[0] == path: # sentinel for absolute paths 
            allparts.insert(0, parts[0]) 
            break 
        elif parts[1] == path: # sentinel for relative paths 
            allparts.insert(0, parts[1]) 
            break 
        else: 
            path = parts[0] 
            allparts.insert(0, parts[1]) 
            return allparts

然后您可以像这样使用它,与os.path.join一起加入:

>>> source_path = '/path/to/a/directory/or/file'
>>> temp = splitall(source_path)
>>> temp
['path', 'to', 'a', 'directory', 'or', 'file']
>>> temp[2] = 'different'
>>> target_path = os.path.join(*temp)
>>> target_path
'path/to/different/directory/or/file'

答案 1 :(得分:0)

如果我理解你想说的话,你想要这个:

source_path = "/path/to/a/directory/or/file.txt"
target_path = source_path.replace("/a/", "/different/", 1)
print target_path

答案 2 :(得分:0)

使用https://docs.python.org/3/library/pathlib.html#module-pathlib

>>> from pathlib import PurePath
>>> import os
>>> path = PurePath("/path/to/a/directory/or/file.txt")
>>> path.parts
('/', 'path', 'to', 'a', 'directory', 'or', 'file.txt')
>>> a_idx = -1
>>> for idx,part in enumerate(path.parts):
...   if part == 'a':
...     a_idx = idx
...     break
... 
>>> a_idx
3
>>> pre_path = os.path.join(*path.parts[:a_idx])
>>> post_path = os.path.join(*path.parts[a_idx+1:])
>>> new_path = os.path.join(pre_path, 'different', post_path)
>>> new_path
'/path/to/different/directory/or/file.txt'

答案 3 :(得分:0)

如果您不知道目录的名称,而只知道其索引:

from pathlib import Path

source_path = Path("/path/to/a/directory/or/file.txt")
unknown_name = source.parts[3] # position including root
target_path = "/".join([part if part != unknown_name else "different" for part in source.parts])[1:]

如果您知道目录的名称但不知道其索引,则几乎相同:

from pathlib import Path

source = Path("/path/to/a/directory/or/file.txt")
src_parts = source.parts
unknown_index = src_parts.index('a')
target_path = "/".join([src_parts[part] if part != unknown_index else "different" for part in range(len(src_parts))])[1:]