pythonstringpath

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


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

"/path/to/some/file.txt"  →  "file"

Solution

  • Python 3.4+

    Use pathlib.Path.stem

    >>> from pathlib import Path
    >>> Path("/path/to/file.txt").stem
    'file'
    >>> Path("/path/to/file.tar.gz").stem
    'file.tar'
    

    Python < 3.4

    Use os.path.splitext in combination with os.path.basename:

    >>> os.path.splitext(os.path.basename("/path/to/file.txt"))[0]
    'file'
    >>> os.path.splitext(os.path.basename("/path/to/file.tar.gz"))[0]
    'file.tar'