How to Get the Filename Without the Extension from a Path in Python

Created
Modified

Using pathlib Module

You can use .stem from pathlib to get the filename without the extension from a path, it really simple. For example,

#!/usr/bin/python3

# Import module
import pathlib

f = "/root/file.txt"
print(pathlib.Path(f).stem)

f = "/root/file.tar.gz"
print(pathlib.Path(f).stem)
file
file.tar

Note that if your file has multiple extensions .stem will only remove the last extension.

Using splitext Method

The os.path.splitext() method splits the pathname path into a pair (root, ext) such that root + ext == path, and the extension, ext, is empty or begins with a period and contains at most one period.

See the following example:

#!/usr/bin/python3

# Import module
import os

f = "/root/file.txt"
print(os.path.splitext(f)[0])
/root/file

Try this:

#!/usr/bin/python3

# Import module
import os

def filename(f):
  base = os.path.basename(f)
  return os.path.splitext(base)[0]

f = "/root/file.txt"
print(filename(f))
file

Related Tags