HoneyBadger
HoneyBadger

Reputation: 3

Splitting file path using Python

Suppose we have two file paths

C:\User\JohnDoe\Desktop\Happy\Happy\Expression\Smile.exe

C:\User\JohnDoe\Desktop\Happy\Expression\Smile.exe

We need to extract file path after the last mention of Happy.

Desired string should be

..\Expression\Smile.exe 

for both cases.

How do we achieve this using python?

I thought of using split function

a = 'C:\\User\\JohnDoe\\Desktop\\Happy\\Happy\\Expression\\Smile.exe'

b = 'C:\\User\\JohnDoe\\Desktop\\Happy\\Expression\\Smile.exe'

print( a.split("Happy"))
print('..'+b.split("Happy")[1])

Output

['C:\\User\\JohnDoe\\Desktop\\', '\\', '\\Expression\\Smile.exe']
..\Expression\Smile.exe

I know that the first print statement is incorrect. Is there any cleaner way of doing this?

Upvotes: 0

Views: 324

Answers (2)

Daweo
Daweo

Reputation: 36510

You might use .rsplit method which accepts maximal number of splits as 2nd argumet:

path1 = r"C:\User\JohnDoe\Desktop\Happy\Happy\Expression\Smile.exe"
path2 = r"C:\User\JohnDoe\Desktop\Happy\Expression\Smile.exe"
print(path1.rsplit("Happy",1)[-1])
print(path2.rsplit("Happy",1)[-1])

output

\Expression\Smile.exe
\Expression\Smile.exe

Upvotes: 1

Vedank Pande
Vedank Pande

Reputation: 446

Use the last element after the split:

a = 'C:\\User\\JohnDoe\\Desktop\\Happy\\Happy\\Expression\\Smile.exe'

print(a.split("Happy")[-1])

output:

\Expression\Smile.exe

Upvotes: 2

Related Questions