我有一個檔案夾 X,里面有很多(超過 500 個)子檔案夾。在這些子檔案夾中,有時我想洗掉一個子檔案夾 TARGET。我正在考慮使用腳本來執行此操作。
我不是python專家,但我嘗試制作這個腳本,在使用它之前有丟失我需要的檔案的風險,你能檢查一下它是否正確嗎??謝謝
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)
uj5u.com熱心網友回復:
在這里,我修復了您的代碼并使其更有用,因此任何人都可以使用它:) 享受
#coded by antoclk @ [email protected]
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!')
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/331205.html
