使用 python 删除许多子文件夹中的目标文件夹
Deleting a target folder in many subfolders with python
我有一个文件夹 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)
在这里,我修正了你的代码并让它更有用,所以任何人都可以使用它:)享受
#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!')
我有一个文件夹 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)
在这里,我修正了你的代码并让它更有用,所以任何人都可以使用它:)享受
#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!')