How to search for a folder name in python and delete it

后端 未结 2 1380
情深已故
情深已故 2021-01-24 02:39

I have a directory of folders and subfolders that I need to search through to find a certain folder name, \"old data\", so that I can delete the files within \"old data\" and de

相关标签:
2条回答
  • 2021-01-24 02:54

    following code is for linux environment but shutil.rmtree() is what you need

    1 import os                                                                                                                                                             
    2 import shutil                                                                  
    3                                                                                
    4 root = "/home/user/input"                                                     
    5 for i in os.walk(root, topdown=False):                                         
    6      if i[0].split('/')[-1] == "test3":                                        
    7          shutil.rmtree(i[0]) 
    

    os.remove() - to remove file os.rmdir() - to remove empty dir shutil.rmtree() - to remove dir and all its content

    0 讨论(0)
  • See if the below code works for your scenario:

    import os
    import shutil
    
    for root, subdirs, files in os.walk('C:/directory'):
        for d in subdirs:
            if d == "old data":
                shutil.rmtree(os.path.join(root, d))
    

    shutil.rmtree will delete the entire "old data" directory

    0 讨论(0)
提交回复
热议问题