Deleting folders in python recursively
删除空目录时遇到问题。这是我的代码:
1 2 3 4 5 6 7 | for dirpath, dirnames, filenames in os.walk(dir_to_search): //other codes try: os.rmdir(dirpath) except OSError as ex: print(ex) |
参数
1 2 3 4 | test/20/... test/22/... test/25/... test/26/... |
请注意,以上所有文件夹都是空的。当我运行这个脚本时,文件夹
我得到的例外是:
1 2 3 4 5 6 7 8 9 10 11 | [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' |
我在哪里犯错?
1 2 | import shutil shutil.rmtree('/path/to/your/dir/') |
默认行为是
在shutil rmtree试试。在Python的标准库
位晚表演,但这里是我的unlinker纯pathlib递归目录
1 2 3 4 5 6 7 8 9 10 | def rmdir(dir): dir = Path(dir) for item in dir.iterdir(): if item.is_dir(): rmdir(item) else: item.unlink() dir.rmdir() rmdir(pathlib.Path("dir/")) |
最好使用绝对路径和进出只有rmtree函数
1 2 | from shutil import rmtree rmtree('directory-absolute-path') |
只是下一个家伙是micropython搜索解决方案,作为一个纯粹的基于本厂(listdir的删除,删除)。它是不完整的(特别是在errorhandling)或幻想,它将工作在大多数情况下,但是。
1 2 3 4 5 6 7 8 9 | def deltree(target): print("deltree", target) for d in os.listdir(target): try: deltree(target + '/' + d) except OSError: os.remove(target + '/' + d) os.rmdir(target) |
该命令给出(有的)不能删除的文件,如果它是只读的。因此,可以使用一个
1 2 3 4 5 6 7 8 9 | import os, sys from stat import * 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) |
解决方案:这是一个递归的
1 2 3 4 5 6 7 8 9 10 11 12 | def clear_folder(dir): if os.path.exists(dir): for the_file in os.listdir(dir): file_path = os.path.join(dir, the_file) try: if os.path.isfile(file_path): os.unlink(file_path) else: clear_folder(file_path) os.rmdir(file_path) except Exception as e: print(e) |