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

前端 未结 3 1835
走了就别回头了
走了就别回头了 2021-02-14 10:10

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 10:55

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

提交回复
热议问题