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.
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.
pathlib. Path (WindowsPath, PosixPath, etc.) objects are not considered PathLike : PY-30747.
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.
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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With