Elegant way to take basename of directory in Python?

后端 未结 5 1341
傲寒
傲寒 2021-02-20 01:30

I have several scripts that take as input a directory name, and my program creates files in those directories. Sometimes I want to take the basename of a directory given to the

相关标签:
5条回答
  • 2021-02-20 01:59

    To deal with your "trailing slash" issue (and other issues!), sanitise user input with os.path.normpath().

    To build paths, use os.path.join()

    0 讨论(0)
  • 2021-02-20 02:06

    to build the paths without writing slashes it is better to use:

    os.path.join(dir, subdir, file)
    

    if you want to add separators or get the separator independly of the os, then use

     os.sep
    
    0 讨论(0)
  • 2021-02-20 02:09

    Manually building up paths is a bad idea for portability; it will break on Windows. You should use os.path.sep.

    As for your first question, using os.path.join is the right idea.

    0 讨论(0)
  • 2021-02-20 02:10

    Use os.path.join() to build up paths. For example:

    >>> import os.path
    >>> path = 'foo/bar'
    >>> os.path.join(path, 'filename')
    'foo/bar/filename'
    >>> path = 'foo/bar/'
    >>> os.path.join(path, 'filename')
    'foo/bar/filename'
    
    0 讨论(0)
  • 2021-02-20 02:12

    You should use os.path.join() to add paths together.

    use

    os.path.dirname(os.path.join(output_dir,''))
    

    to extract dirname, while adding a trailing slash if it was omitted.

    0 讨论(0)
提交回复
热议问题