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

ε祈祈猫儿з 提交于 2020-12-01 09:51:32

问题


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


回答1:


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])



回答2:


To add a trailing slash of the path's flavour using just pathlib you could do:

>>> from pathlib import Path
>>> my_path = Path("abc/def")
>>> str(my_path / "_")[:-1]  # add a dummy "_" component, then strip it
'abc/def/'

Looking into the source, there's also a Path._flavour.sep attribute:

>>> str(my_path) + my_path._flavour.sep
'abc/def/'

But it doesn't seem to have any documented accessor yet.




回答3:


You could also use:

os.path.normpath(str(my_path)) + os.sep

I would say it is down to preference rather than being "nicer"



来源:https://stackoverflow.com/questions/47572165/whats-the-best-way-to-add-a-trailing-slash-to-a-pathlib-directory

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!