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

前端 未结 23 2109
逝去的感伤
逝去的感伤 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:37

    A multiple extension aware procedure. Works for str and unicode paths. Works in Python 2 and 3.

    import os
    
    def file_base_name(file_name):
        if '.' in file_name:
            separator_index = file_name.index('.')
            base_name = file_name[:separator_index]
            return base_name
        else:
            return file_name
    
    def path_base_name(path):
        file_name = os.path.basename(path)
        return file_base_name(file_name)
    

    Behavior:

    >>> path_base_name('file')
    'file'
    >>> path_base_name(u'file')
    u'file'
    >>> path_base_name('file.txt')
    'file'
    >>> path_base_name(u'file.txt')
    u'file'
    >>> path_base_name('file.tar.gz')
    'file'
    >>> path_base_name('file.a.b.c.d.e.f.g')
    'file'
    >>> path_base_name('relative/path/file.ext')
    'file'
    >>> path_base_name('/absolute/path/file.ext')
    'file'
    >>> path_base_name('Relative\\Windows\\Path\\file.txt')
    'file'
    >>> path_base_name('C:\\Absolute\\Windows\\Path\\file.txt')
    'file'
    >>> path_base_name('/path with spaces/file.ext')
    'file'
    >>> path_base_name('C:\\Windows Path With Spaces\\file.txt')
    'file'
    >>> path_base_name('some/path/file name with spaces.tar.gz.zip.rar.7z')
    'file name with spaces'
    

提交回复
热议问题