How to get the filename without the extension from a path in Python?

前端 未结 23 1468
逝去的感伤
逝去的感伤 2020-11-22 05:43

How to get the filename without the extension from a path in Python?

For instance, if I had "/path/to/some/file.txt", I would want "

23条回答
  •  抹茶落季
    2020-11-22 06:45

    You can make your own with:

    >>> import os
    >>> base=os.path.basename('/root/dir/sub/file.ext')
    >>> base
    'file.ext'
    >>> os.path.splitext(base)
    ('file', '.ext')
    >>> os.path.splitext(base)[0]
    'file'
    

    Important note: If there is more than one . in the filename, only the last one is removed. For example:

    /root/dir/sub/file.ext.zip -> file.ext
    
    /root/dir/sub/file.ext.tar.gz -> file.ext.tar
    

    See below for other answers that address that.

提交回复
热议问题