1

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!

chanwcom
  • 3,952
  • 6
  • 33
  • 43
  • [`os.path.splitext`](https://docs.python.org/2/library/os.path.html#os.path.splitext) – khelwood Nov 02 '16 at 16:50
  • 1
    Possible duplicate of [How to get the filename without the extension from a path in Python?](http://stackoverflow.com/questions/678236/how-to-get-the-filename-without-the-extension-from-a-path-in-python) – asongtoruin Nov 02 '16 at 16:51

3 Answers3

3

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))
user2357112
  • 235,058
  • 25
  • 372
  • 444
2

Instead of using regular expressions, you can use the power of Python's os.path module - combine os.path.basename() and os.path.splitext():

In [1]: import os

In [2]: filename = "/experimental/users/nerd/wavfiles/wavfile0722.wav"

In [3]: os.path.splitext(os.path.basename(filename))[0]
Out[3]: 'wavfile0722'
Community
  • 1
  • 1
alecxe
  • 441,113
  • 110
  • 1,021
  • 1,148
1

You could use os.path.splitext instead of a regex. It returns a 2 elements tuple containing the name and the extension

Tryph
  • 5,517
  • 26
  • 46