0

I have a string path='/home/user/Desktop/My_file.xlsx'.

I want to extract the "My_file" substring. I am using Django framework for python.

I have tried to get it with:

re.search('/(.+?).xlsx', path).group(1)

but it returns the whole path again.
Can someone please help.

zubergu
  • 3,646
  • 3
  • 25
  • 38
  • 2
    Related: [Get filename without extension in Python](http://stackoverflow.com/questions/678236/how-to-get-the-filename-without-the-extension-from-a-path-in-python) – Kyle Pittman Oct 13 '15 at 12:49

3 Answers3

2

If you know that the file extension is always the same (e.g. ".xlsx") I would suggest you to go this way:

import os
filename_full = os.path.basename(path)
filename = filename_full.split(".xlsx")[0]

Hope it helps

FSp
  • 1,545
  • 17
  • 37
0

More generally:

import os
filename = os.path.basename(os.path.splitext(path)[0])
albar
  • 3,020
  • 1
  • 14
  • 27
-1
If you need to match the exact extension:
# (?<=/) ensure that before the match is / 
# [^/]*.xlsx search for anything but / followed by .xlsx
mo1 = re.search('(?<=/)[^/]*.xlsx', path).group(0)
print(mo1)
My_file.xlsx

otherwise:

path='/home/user/Desktop/My_file.xlsx'

with regex:

mo = re.search(r'(?<=/)([\w.]+$)',path)
print(mo.group(1))
My_file.xlsx

with rsplit:

my_file = path.rsplit('/')[-1]
print(my_file)
My_file.xlsx
LetzerWille
  • 5,355
  • 4
  • 23
  • 26
  • What actual problem i had was i was searching "My_file" in b/w "/" and ".xlsx". but it was using "/" which is before home. and i was very curious to know how to use "/" which comes before the file name. Thank you so much again. Sory if i was unable to explain the question properly. –  Oct 13 '15 at 13:56
  • @AmanGupta here is good explanation http://www.regular-expressions.info/lookaround.html – LetzerWille Oct 13 '15 at 14:06
  • Thnak you so much for the help. Can you please helpme with the select query in django. Django tutorial is not well specified with an example. for eg. Select id from student where name="abc" how to write these in django –  Oct 13 '15 at 14:20
  • @AmanGupta the solution you chose does not work, e.g., on a filesystem that uses the backslash as path separator. Also, working with regexp in this case you produce less readable (and thus maintainable) code. Since you work with file paths (and not generic strings) I really suggest you to use the python `os` library – FSp Oct 13 '15 at 14:32