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

前端 未结 3 2126
囚心锁ツ
囚心锁ツ 2021-02-14 10:20

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

3条回答
  •  南笙
    南笙 (楼主)
    2021-02-14 11:03

    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.

提交回复
热议问题