def getDirs(path):
sub = os.listdir(path)
paths = []
for p in sub:
pDir = '{}\{}'.format(path, p)
if os.path.isdir(pDir):
paths.extend(getAllFiles(pDir, paths)) # getAllFiles is the same as above
else:
paths.append(pDir)
return paths
import os, shutil
folder = "C:\Windows\CSC\v2.0.6\namespace"
for item in os.listdir(folder):
path = os.path.join(folder, item)
try:
os.unlink(path) # delete if the item is a file
except Exception as e:
shutil.rmtree(path) # delete if the item is a folder
一个simple Google search和一些修改:
如果您想递归地找到所有文件,然后将其全部删除(这是我昨天写的一个小脚本):
^{pr2}$所以你可以:
注意:如果有太多的子文件夹(它会创建很多递归节点),递归算法会变得有些慢(并且可能会引发一个
MemoryError
)。在要避免这种情况,可以将递归函数用作辅助函数,该函数由主迭代函数调用:
但是,对于非常大的子文件夹,它会变得很慢。对我来说,浏览
C:\Python27\Lib
大约需要6-7秒(它有大约5k+个文件,还有很多很多子文件夹)。在此代码应删除目录中的所有文件或目录:
这是answered previously。在
相关问题 更多 >
编程相关推荐