Get Filename Without Extension in Python

Get Filename Without Extension in Python

Asked on January 11, 2019 in Regex.
Add Comment


  • 9 Answer(s)

    Get Filename Without Extension in Python for that use:

    os.path.splitext(filename)[0]
    
    

    Above code handle a filename like .bashrc correctly by keeping the whole name.

     

    Answered on January 11, 2019.
    Add Comment

    Alternately use this code for Get Filename Without Extension in Python:

    >>> import os
    >>> os.path.splitext("1.1.1.1.1.jpg")
    ('1.1.1.1.1', '.jpg')
    
    Answered on January 11, 2019.
    Add Comment

    >>> 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’

    Getting the name of file without the extension :
    import os
    print(os.path.splitext(“path_to_file”)[0])

    Answered on February 5, 2019.
    Add Comment

    Get Filename Without Extension in Python

    Answered on May 20, 2019.
    Add Comment
    >>> 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'
    Answered on May 20, 2019.
    Add Comment
    >>> file = '/root/dir/sub.exten/file.data.1.2.dat'
    >>> print ('.').join(file.split('.')[:-1])
    /root/dir/sub.exten/file.data.1.2
    Answered on May 20, 2019.
    Add Comment
    >>> 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
    Answered on May 20, 2019.
    Add Comment
    >>> from pathlib import Path
    >>> p = Path("/a/b/c.txt")
    >>> print(p.with_suffix(''))
    \a\b\c
    >>> print(p.stem)
    c
    Answered on May 20, 2019.
    Add Comment
    >>> import os
    >>> path = 'my_text_file.txt'
    >>> root, ext = os.path.splitext(path)
    >>> root
    'my_text_file'
    >>> ext
    '.txt'
    Answered on May 20, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.