chanwcom chanwcom - 1 year ago 67
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:
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 Source

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))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download