Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to add a trailing slash to a pathlib directory?

Tags:

python

pathlib

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), '')?

like image 435
Tom Avatar asked Nov 30 '17 11:11

Tom


People also ask

How do I add a slash to a directory in Python?

join(path, '') will add the trailing slash if it's not already there. You can do os. path. join(path, '', '') or os.

What does path from Pathlib do?

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.

How can we create a directory with the Pathlib module?

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 .

What is OS path join in Python?

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.


1 Answers

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])
like image 157
PM 2Ring Avatar answered Sep 19 '22 13:09

PM 2Ring