如何从在parts
中使用pathlib
构建的元组中返回实际的字符串路径?
from pathlib import Path
p = Path(path)
parts_tuple = p.parts
parts_tuple = parts_arr[:-4]
我们得到像('/', 'Users', 'Yohan', 'Documents')
如何将parts_tuple
转换为字符串路径-例如,除第一个数组项(因为它是根部分-“ /”)外,每个部分都以'/'分隔。我很想得到一个字符串作为输出。
答案 0 :(得分:3)
如果您使用的是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'
答案 1 :(得分:2)
您还可以使用内置的OS库,以保持各个OS的一致性。
a = ['/', 'Users', 'Yohan', 'Documents']
os.path.join(*a)
输出:
'/Users/Yohan/Documents'
答案 2 :(得分:1)
您应遵循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'
答案 3 :(得分:0)
>>> path = "C:/Users/Plankton/Desktop/junk.txt/1/2/3/4"
>>> from pathlib import Path
>>> p = Path(path)
>>> p.parents[3]
PosixPath('C:/Users/Plankton/Desktop/junk.txt')
使用parents
属性很有趣,因为它保留了Path对象。