I have a directory I'd like to print out with a trailing slash: my_path = pathlib.Path('abc/def')
Is there a nicer way of doing this than os.path.join(str(my_path), '')
?
join(path, '') will add the trailing slash if it's not already there. You can do os. path. join(path, '', '') or os.
The path is used to identify a file. The path provides an optional sequence of directory names terminated by the final file name including the filename extension. The filename extension provides some information about the file format/ contents. The Pathlib module can deal with absolute as well as relative paths.
Create Directory in Python Using the Path. mkdir() Method of the pathlib Module. The Path. mkdir() method, in Python 3.5 and above, takes the path as input and creates any missing directories of the path, including the parent directory if the parents flag is True .
path. join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator ('/') following each non-empty part except the last path component.
No, you didn't miss anything. By design, pathlib
strips trailing slashes, and provides no way to display paths with trailing slashes. This has annoyed several people, as mentioned in the bug tracker: pathlib strips trailing slash.
A compact way to add slashes in Python 3.6 is to use an f-string, eg f'{some_path}/'
or f'{some_path}{os.sep}'
if you want to be OS-agnostic.
from pathlib import Path
import os
some_path = '/etc'
p = Path(some_path)
print(f'{p}/')
print(f'{p}{os.sep}')
output
/etc/
/etc/
Another option is to add a dummy component and slice it off the resulting string:
print(str(p/'@')[:-1])
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