Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get rid of extensions from file basename using python

Tags:

python

regex

I have got the complete path of files in a list like this:

a = ['home/robert/Documents/Workspace/datafile.xlsx', 'home/robert/Documents/Workspace/datafile2.xls', 'home/robert/Documents/Workspace/datafile3.xlsx']

what I want is to get just the file NAMES without their extensions, like:

b = ['datafile', 'datafile2', 'datafile3']

What I have tried is:

xfn = re.compile(r'(\.xls)+')
for name in a:
    fp, fb = os.path.split(fp)
    ofn = xfn.sub('', name)
    b.append(ofn)

But it results in:

b = ['datafilex', 'datafile2', 'datafile3x']
like image 275
MHS Avatar asked Apr 06 '13 10:04

MHS


1 Answers

This is a repeat of: How to get the filename without the extension from a path in Python?

https://docs.python.org/3/library/os.path.html

In python 3 pathlib "The pathlib module offers high-level path objects." so,

>>> from pathlib import Path
>>> p = Path("/a/b/c.txt")
>>> print(p.with_suffix(''))
\a\b\c
>>> print(p.stem)
c
like image 75
jjisnow Avatar answered Sep 22 '22 09:09

jjisnow