0

This should be a vary basic thing to do, but I can't get it to work despite following a lot of examples from the web. What I'm trying is to use the sub function to get the name of a file from a complete path.

So, if

output="/home/alvarofeal/Desktop/prueba_sub.avi"
re.sub(r'(.*\/)*', "", output)
print output

output: /home/alvarofeal/Desktop/prueba_sub.avi

Shouldn't the output be:

prueba_sub.avi
0

3 Answers 3

2

re.sub() returns a new string. Strings are immutable and cannot be changed in-place.

You are ignoring the return value; store it back in output if you want to replace the old value:

output = "/home/alvarofeal/Desktop/prueba_sub.avi"
output = re.sub(r'(.*\/)*', "", output)
print output

If all you are doing is splitting the basename of a file path, you probably want to use the os.path.basename() function instead though.

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

1 Comment

Rookie mistake, that worked to perfection, validating the answer as soon as I can!
1

You have to do,

output = re.sub(r'(.*\/)*', "", output)

since re.sub() returns new string

OR using ntpath

>>>import ntpath
>>>ntpath.basename(output)
'prueba_sub.avi'

2 Comments

why are you using ntpath?
i think it is platform independent(forward slash and backward slash also)
1

You don't need regex for this task.As a more pythonic way you can use os.path.basename with str.split:

>>> os.path.basename('/home/alvarofeal/Desktop/prueba_sub.avi').split('.')[0]
'prueba_sub'

or just use basename to get the name with format :

>>> os.path.basename('/home/alvarofeal/Desktop/prueba_sub.avi')
'prueba_sub.avi'

1 Comment

I needed to use regex because it's for school purposes, but your answer was helpful in case I sometime need to do it for my own program. Thanks

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.