Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

From pathlib parts tuple to string path

Tags:

python

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.

like image 972
YohanRoth Avatar asked Nov 12 '18 03:11

YohanRoth


People also ask

What does Pathlib path () do?

The pathlib is a Python module which provides an object API for working with files and directories. The pathlib is a standard module. Path is the core object to work with files.

Is Pathlib path PathLike?

pathlib. Path (WindowsPath, PosixPath, etc.) objects are not considered PathLike : PY-30747.

What is path () in Python?

PYTHONPATH is an environment variable which the user can set to add additional directories that the user wants Python to add to the sys. path directory list. In short, we can say that it is an environment variable that you set before running the Python interpreter.

Why is Pathlib better than os path?

Pathlib allows you to easily iterate over that directory's content and also get files and folders that match a specific pattern. Remember the glob module that you used to import along with the os module to get paths that match a pattern?


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'
like image 134
florisla Avatar answered Oct 26 '22 16:10

florisla


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'
like image 26
LeKhan9 Avatar answered Oct 26 '22 14:10

LeKhan9


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'
like image 21
Red Cricket Avatar answered Oct 26 '22 15:10

Red Cricket


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

like image 31
tbrittoborges Avatar answered Oct 26 '22 16:10

tbrittoborges