chanwcom chanwcom - 1 month ago 9
Python Question

What is the best way to select the base name portion of the path excluding the extension in Python?

I would like to select the base name portion of a file path excluding the file extension.

For example, if the path is something like the following:
/experimental/users/nerd/wavfiles/wavfile0722.wav
Then, I would like to select "wavefile0722" portion of the above path.

I have been using the following statement in Python for this purpose.

basename_wo_ext = re.sub('\.[^\.]*', '' , os.path.basename(file_path))


But I wonder whether it is a good approach or not, and if not, what would be the best way for this case.

Any suggestions are welcomed. Thank you!

Answer

os.path also includes the splitext function for splitting the extension off of a path:

basename_wo_ext, possible_ext = os.path.splitext(os.path.basename(file_path))
Comments