Python - How to get filename without extension

By xngo on June 17, 2019

In Python, it is easy to get the filename without the extension. You simply need to use splitext() function. This function will return 2 parts: the filename part and the extension part. Here is how to use it.

#!/usr/bin/python3
import os
 
# File path example.
path="/some/file.with spaces.dot.docx"
 
# Get the filename only from the initial file path.
filename = os.path.basename(path)
 
# Use splitext() to get filename and extension separately.
(file, ext) = os.path.splitext(filename)
 
# Print outcome.
print("Filename without extension =", file)
print("Extension =", ext)

Output

Filename without extension = file.with spaces.dot
Extension = .docx

Github

  • https://github.com/xuanngo2001/python-examples/blob/master/io/filename-no-extension.py

About the author

Xuan Ngo is the founder of OpenWritings.net. He currently lives in Montreal, Canada. He loves to write about programming and open source subjects.