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.

1

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

Comments

0

More generally:

import os
filename = os.path.basename(os.path.splitext(path)[0])

Comments

-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

4 Comments

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.
@AmanGupta here is good explanation regular-expressions.info/lookaround.html
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
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.