0

I have tried this code but it didnt work how to remove the path from String.help me to remove the path of directories from the string

string=""
count=0
for file in glob.glob(r'G:\\songs\\My Fav\\*'):
    string=string+"{}. {}\n".format(count,file)
    count+=1
string=string.replace("G:\\songs\\My Fav\\","")
print(string)

OUTPUT for above code is :

0. G:\\songs\\My Fav\0001.mp3
1. G:\\songs\\My Fav\0002.mp3
2. G:\\songs\\My Fav\0003.mp3
3. G:\\songs\\My Fav\0004.mp3
4. G:\\songs\\My Fav\0005.mp3

But i need output without the path, like this below

0. 0001.mp3
1. 0002.mp3
2. 0003.mp3
string=string.replace("G:\\songs\\My Fav\","")

and this above line i have tried shows error

2

4 Answers 4

2

The problem is because \ escapes the next character, so the replace is actually looking for single \ and not doubles \\.

You can use split

string.split("\\")[-1]

Maybe cleaner would be to use os.path.basename to extract the file name. Cf the documentation

1

This is most certainly duplicated, but I don't have a link, try this:

import os
os.path.basename(string)

os.path has specialized functions dedicated to manipulating paths.

0

yes its worked,i have tried like this . thank you so much

import os
string=""
count=0
for file in glob.glob(r'G:\\songs\\My Fav\\*'):
    file=os.path.basename(file)
    string=string+"{}. {}\n".format(count,file)
    count+=1
print(string)```
0

Why don't you try indexing? it is bit long process but it is easy to understand and replicate.

like this -

print(stirng[17:]) # I counted the them so you don't have to count.
1
  • no its not worked string="185. G:\\songs\\My Fav\Yogi_B_&_Natchatra_-_Madai_Thiranthu_featurin’_Mista_G(256k).mp3" print(string[17:]) Commented Mar 13, 2021 at 11:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.