From pathlib parts tuple to string path

Viewed 4231

How to get from tuple constructed by using parts in pathlib back to actual string path?

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

We get smth like ('/', 'Users', 'Yohan', 'Documents')

How to turn parts_tuple to a string path - e.g delimit every part by '/' except first array item (because it is root part - "/"). I care to get a string as an output.

4 Answers

If you're using pathlib then there's no need to use os.path.

Supply the parts to the constructor of Path to create a new Path object.

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

You should follow LeKhan9 answer. Suppose a windows OS. 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'
>>> 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.

Related