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

Zoro
  • 420
  • 5
  • 16
Kongu B K Riot
  • 117
  • 1
  • 6
  • See: https://stackoverflow.com/questions/3548673/how-to-replace-or-strip-an-extension-from-a-filename-in-python – sander Mar 13 '21 at 10:56
  • don't escape the backslash if you're passing a raw string. just run `for file in glob.glob(r'G:\songs\My Fav\*'):` – RJ Adriaansen Mar 13 '21 at 11:04

4 Answers4

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

FlorianGD
  • 2,336
  • 1
  • 15
  • 32
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.

joao
  • 2,220
  • 2
  • 11
  • 15
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)```
Kongu B K Riot
  • 117
  • 1
  • 6
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.
SnehE
  • 13
  • 1
  • 3
  • no its not worked string="185. G:\\songs\\My Fav\Yogi_B_&_Natchatra_-_Madai_Thiranthu_featurin’_Mista_G(256k).mp3" print(string[17:]) – Kongu B K Riot Mar 13 '21 at 11:08