shell 使用python删除多个子文件夹中的目标文件夹

pkln4tw6  于 2022-11-30  发布在  Shell
关注(0)|答案(2)|浏览(191)

我有一个文件夹X,其中有许多(超过500)子文件夹。在这些子文件夹中,有时有一个子文件夹TARGET,我想删除。我正在考虑使用脚本来做这件事。
我不是PythonMaven,但我试图使这个脚本,在使用它之前,冒着丢失我需要的文件的风险,你能请检查它是否正确吗?谢谢

import os
import shutil
dir = '/Volume/X'
targetDir = 'myDir'

for subdir, dirs, files in os.walk(dir):
    dirpath = subdir
    if dirpath.exists() and dirpath.is_dir():
    shutil.rmtree(dirpath)
2hh7jdfx

2hh7jdfx1#

在这里,我修复了你的代码,使它更有用,所以任何人都可以使用它:)享受

#coded by antoclk @ antonioaunix@gmail.com
import os
import shutil

#in dir variable you should put the path you need to scan
dir = '/Users/YOURUSERNAME/Desktop/main' 
#in target variable you should put the exact name of the folder you want to delete. Be careful to use it, it will delete all the files and subfolders contained in the target dir.
target = 'x'

os.system('cls') 
os.system('clear')

print('Removing '+target+' folder from '+dir+' and all its subfolders.')

for dirpath, dirnames, filenames in os.walk(dir):
    for item in dirnames:
        fullPath = os.path.join(dirpath, item)
        #print(os.path.join(dirpath, item))
        if item == 'target':
            print('deleting '+fullPath)
            shutil.rmtree(fullPath)

print('Task completed!')
jtw3ybtb

jtw3ybtb2#

修正了在if item == 'target'级别上的一个小错误。它必须是if item == target,并且重新构造了代码。

import shutil
import os

class FolderCleaner:
    @staticmethod
    def _init(target: str, dirname: str) -> None:
        print(f"Removing '{target}' from '{dirname}' and all it's sub-folders")

    @staticmethod
    def _reset_view() -> None:
        os.system("cls")
        os.system("clear")
    
    @staticmethod
    def delete_all_folders(dirname: str, folder_name: str) -> None:
        FolderCleaner._reset_view()
        FolderCleaner._init(target=folder_name, dirname=dirname)
        for dir_path, dir_names, filenames in os.walk(dirname):
            for item in dir_names:
                full_path = os.path.join(dir_path, item)
                if item == folder_name:
                    print(f"deleting {full_path}")
                    shutil.rmtree(full_path)
        print("Task completed!")

if __name__ == "__main__":
    FolderCleaner.delete_all_folders(dirname="./", folder_name="__pycache__")

相关问题