从 pathlib 部分元组到字符串路径

Yoh*_*oth 6 python

如何从使用partsin构造的元组pathlib返回到实际字符串路径?

from pathlib import Path    
p = Path(path)
parts_tuple = p.parts
parts_tuple = parts_arr[:-4]
Run Code Online (Sandbox Code Playgroud)

我们得到 smth 像 ('/', 'Users', 'Yohan', 'Documents')

如何转向parts_tuple字符串路径 - 例如,除第一个数组项外,用'/'分隔每个部分(因为它是根部分 - “/”)。我想得到一个字符串作为输出。

flo*_*sla 6

如果您正在使用,pathlib则无需使用os.path.

将部件提供给 的构造函数Path以创建新的 Path 对象。

>>> Path('/', 'Users', 'Yohan', 'Documents')
WindowsPath('/Users/Yohan/Documents')

>>> Path(*parts_tuple)
WindowsPath('/Users/Yohan/Documents')

>>> path_string = str(Path(*parts_tuple))
'\\Users\\Yohan\\Documents'
Run Code Online (Sandbox Code Playgroud)


小智 2

您还可以使用内置的操作系统库来保持跨操作系统的一致性。

a = ['/', 'Users', 'Yohan', 'Documents']
os.path.join(*a)
Run Code Online (Sandbox Code Playgroud)

输出:

'/Users/Yohan/Documents'
Run Code Online (Sandbox Code Playgroud)