用pythonrecursion删除文件夹
我在删除空的目录有问题。 我有这样的代码:
for dirpath, dirnames, filenames in os.walk(dir_to_search): //other codes try: os.rmdir(dirpath) except OSError as ex: print(ex)  参数dir_to_search是我传递工作需要closures的目录的地方。 该目录如下所示: 
 test/20/... test/22/... test/25/... test/26/... 
 请注意,上述所有文件夹都是空的。 当我运行这个脚本时,文件夹25就被删除了! 但是,文件夹25和26不会被删除,即使它们是空文件夹。 
编辑:
我得到的例外是:
 [Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test' [Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012' [Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10' [Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/29' [Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/29/tmp' [Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/28' [Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/28/tmp' [Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/26' [Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/25' [Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/27' [Errno 39] Directory not empty: '/home/python-user/shell-scripts/s3logs/test/2012/10/27/tmp' 
我在哪里犯错误
提前致谢。
试试shutil模块:
 import shutil shutil.rmtree('/path/to/your/dir/') 
  os.walk()的默认行为是从根到叶。 在os.walk()设置topdown=False从叶子到根。 
尝试rmtree在shutil 。 在python std库中
 最好使用绝对path,只from shutil import rmtree rmtree函数from shutil import rmtree因为这是一个大的包,上面的行只会导入所需的函数。 
 from shutil import rmtree rmtree('directory-absolute-path') 
命令(由Tomek提供) 不能删除文件,如果它是只读的 。 因此,可以使用 –
 def del_evenReadonly(action, name, exc): os.chmod(name, stat.S_IWRITE) os.remove(name) if os.path.exists("test/qt_env"): shutil.rmtree('test/qt_env',onerror=del_evenReadonly)