如何在Python中的文件路径中间插入目录?

NeS*_*ack 6 python path filepath os.path

我想在给定文件路径的中间插入一个目录名,如下所示:

directory_name = 'new_dir'
file_path0 = 'dir1/dir2/dir3/dir4/file.txt'
file_path1 = some_func(file_path0, directory_name, position=2)
print(file_path1)
>>> 'dir1/dir2/new_dir/dir3/dir4/file.txt'
Run Code Online (Sandbox Code Playgroud)

我查看了 os.path 和 pathlib 包,但看起来它们没有允许在文件路径中间插入的功能。我试过:

import sys,os
from os.path import join

path_ = file_path0.split(os.sep)
path_.insert(2, 'new_dir')
print(join(path_))
Run Code Online (Sandbox Code Playgroud)

但这会导致错误

“需要 str、bytes 或 os.PathLike 对象,而不是列表”

有谁知道允许在文件路径中间插入这样的标准Python函数?或者 - 我怎样才能转向path_可以处理的东西os.path。我是 pathlib 的新手,所以也许我错过了一些东西


编辑:根据问题的答案,我可以建议以下解决方案:

1.)正如 Zach Favakeh 所建议的和这个答案join(*path_)中所写的那样,只需使用“splat”运算符将上面的代码更正即可*,一切都解决了。

2.)按照buran的建议,您可以使用该pathlib软件包,简而言之,它会导致:

from pathlib import PurePath

path_list = list(PurePath(file_path0).parts)
path_list.insert(2, 'new_dir')
file_path1 = PurePath('').joinpath(*path_list)

print(file_path1)
>>> 'dir1/dir2/new_dir/dir3/dir4/file.txt'
Run Code Online (Sandbox Code Playgroud)

Zac*_*keh 2

由于您想在列表上使用 join 来生成路径名,因此您应该使用“splat”运算符执行以下操作:Python os.path.join() on a list

编辑:您还可以使用 np.array2string 将 np 数组连接到字符串中,使用“/”作为分隔符参数:https://docs.scipy.org/doc/numpy-1.14.0/reference/生成/numpy.array2string.html

希望这可以帮助。