Elegant way to take basename of directory in Python?

混江龙づ霸主 提交于 2019-12-04 02:13:15

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

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

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'

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.

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.

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