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

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

    os.path.splitext() won't work if there are multiple dots in the extension.

    For example, images.tar.gz

    >>> import os
    >>> file_path = '/home/dc/images.tar.gz'
    >>> file_name = os.path.basename(file_path)
    >>> print os.path.splitext(file_name)[0]
    images.tar
    

    You can just find the index of the first dot in the basename and then slice the basename to get just the filename without extension.

    >>> import os
    >>> file_path = '/home/dc/images.tar.gz'
    >>> file_name = os.path.basename(file_path)
    >>> index_of_dot = file_name.index('.')
    >>> file_name_without_extension = file_name[:index_of_dot]
    >>> print file_name_without_extension
    images
    

提交回复
热议问题