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.

import os
# File path example.
# 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)


Filename without extension = file.with
Extension = .docx



About the author

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