简体   繁体   English

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

[英]From pathlib parts tuple to string path

How to get from tuple constructed by using parts in pathlib back to actual string path?如何从使用pathlib parts构造的元组返回到实际的字符串路径?

from pathlib import Path    
p = Path(path)
parts_tuple = p.parts
parts_tuple = parts_arr[:-4]

We get smth like ('/', 'Users', 'Yohan', 'Documents')我们得到类似('/', 'Users', 'Yohan', 'Documents')

How to turn parts_tuple to a string path - eg delimit every part by '/' except first array item (because it is root part - "/").如何将parts_tuple转换为字符串路径-例如,除第一个数组项外,用'/' 分隔每个部分(因为它是根部分-“/”)。 I care to get a string as an output.我想得到一个字符串作为输出。

If you're using pathlib then there's no need to use os.path .如果您使用pathlib则无需使用os.path

Supply the parts to the constructor of Path to create a new Path object.将部件提供给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'

You should follow LeKhan9 answer.您应该遵循 LeKhan9 的回答。 Suppose a windows OS.假设一个 Windows 操作系统。 We would have:我们会有:

>>> 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'

You can also use the built in OS lib, to keep consistency across OSs.您还可以使用内置的操作系统库来保持跨操作系统的一致性。

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

output:输出:

'/Users/Yohan/Documents'
>>> 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')

Using the parents attribute is intersting because it preserves the Path object.使用parents属性很有趣,因为它保留了 Path 对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM