【问题标题】:how to remove folder path from a string in python如何从python中的字符串中删除文件夹路径
【发布时间】:2021-03-13 10:50:23
【问题描述】:

我已经尝试过这段代码,但它没有工作如何从字符串中删除路径。帮助我从字符串中删除目录路径

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)

以上代码的输出是:

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

但我需要没有路径的输出,如下所示

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

我试过的上面这行显示错误

【问题讨论】:

标签: python


【解决方案1】:

问题是因为\ 转义了下一个字符,所以replace 实际上是在寻找单\ 而不是双\\

你可以使用split

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

也许更简洁的方法是使用os.path.basename 来提取文件名。参考documentation

【讨论】:

    【解决方案2】:

    这肯定是重复的,但我没有链接,试试这个:

    import os
    os.path.basename(string)
    

    os.path 具有专门用于操纵路径的专用函数。

    【讨论】:

      【解决方案3】:

      是的,它有效,我试过这样。非常感谢

      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)```
      

      【讨论】:

        【解决方案4】:

        您为什么不尝试索引? 这个过程有点长,但很容易理解和复制。

        像这样 -

        print(stirng[17:]) # I counted the them so you don't have to count.
        

        【讨论】:

        • 不,它不起作用 string="185.G:\\songs\\My Fav\Yogi_B_&_Natchatra_-_Madai_Thiranthu_featurin'_Mista_G(256k).mp3" print(string[17:])
        猜你喜欢
        • 2022-01-12
        • 1970-01-01
        • 1970-01-01
        • 2011-04-22
        • 2010-09-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多