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

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

    @IceAdor's refers to rsplit in a comment to @user2902201's solution. rsplit is the simplest solution that supports multiple periods.

    Here it is spelt out:

    file = 'my.report.txt'
    print file.rsplit('.', 1)[0]
    

    my.report

    0 讨论(0)
  • 2020-11-22 06:43

    On Windows system I used drivername prefix as well, like:

    >>> s = 'c:\\temp\\akarmi.txt'
    >>> print(os.path.splitext(s)[0])
    c:\temp\akarmi
    

    So because I do not need drive letter or directory name, I use:

    >>> print(os.path.splitext(os.path.basename(s))[0])
    akarmi
    
    0 讨论(0)
  • 2020-11-22 06:44
    import os
    path = "a/b/c/abc.txt"
    print os.path.splitext(os.path.basename(path))[0]
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-22 06:46

    Getting the name of the file without the extension:

    import os
    print(os.path.splitext("/path/to/some/file.txt")[0])
    

    Prints:

    /path/to/some/file
    

    Documentation for os.path.splitext.

    Important Note: If the filename has multiple dots, only the extension after the last one is removed. For example:

    import os
    print(os.path.splitext("/path/to/some/file.txt.zip.asc")[0])
    

    Prints:

    /path/to/some/file.txt.zip
    

    See other answers below if you need to handle that case.

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