Reputation: 117
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
Upvotes: 0
Views: 2483
Reputation: 2436
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
Upvotes: 2
Reputation: 23
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.
Upvotes: 0
Reputation: 117
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)```
Upvotes: 0
Reputation: 2293
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.
Upvotes: 1