Python 从pathlib部件元组到字符串路径

Python 从pathlib部件元组到字符串路径,python,Python,如何从使用pathlib中的parts构造的元组返回到实际的字符串路径 from pathlib import Path p = Path(path) parts_tuple = p.parts parts_tuple = parts_arr[:-4] 我们得到的smth像('/','Users','Yohan','Documents') 如何将parts\u tuple转换为字符串路径-例如,除第一个数组项外,用“/”分隔每个部分(因为它是根部分-“/”)。我想得到一个字符串作为输出

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

from pathlib import Path    
p = Path(path)
parts_tuple = p.parts
parts_tuple = parts_arr[:-4]
我们得到的smth像
('/','Users','Yohan','Documents')


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

您应该按照LeKhan9的答案。假设一个windows操作系统。我们会:

>>> path = "C:/Users/Plankton/Desktop/junk.txt
>>> import os
>>> from pathlib import Path    
>>> p = Path(path)
>>> os.path.join(*p.parts)
'C:\\Users\\Plankton\\Desktop\\junk.txt'

您还可以使用内置的OS库,以保持整个OSs的一致性

a = ['/', 'Users', 'Yohan', 'Documents']
os.path.join(*a)
输出:

'/Users/Yohan/Documents'

使用
parents
属性很有趣,因为它保留了Path对象

如果您使用的是
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'

如何:
'/{}.format('/'.join(a[1:])
?抱歉,刚刚注意到它是元组类型,而不是数组下面的解决方案和上面的注释仍然适用于元组类型:)os.path.join(list(parts_tuple))当我这样做时,我会得到错误类型错误:预期的str、bytes或os.PathLike对象,而不是listops。六羟甲基三聚氰胺六甲醚。。不知道star在做什么,但它做了一个小技巧。star将迭代器、列表、元组等扩展为一个以逗号分隔的平面参数sbtw,您不需要将其转换为列表,您也可以对元组执行操作,以稍微提高效率:)
>>> Path('/', 'Users', 'Yohan', 'Documents')
WindowsPath('/Users/Yohan/Documents')

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

>>> path_string = str(Path(*parts_tuple))
'\\Users\\Yohan\\Documents'