python - python中删除多个目录

标签 python directory shutil

在 python 中,我知道我可以使用以下命令删除多个同名文件,例如:

for f in glob.glob("file_name_*.txt"):
    os.remove(f)

并且可以使用 shutil.rmtree('/path/to/dir') 删除单个目录- 即使该目录不为空,该命令也会删除该目录。另一方面,os.rmdir()需要该目录为空。

我其实想删除多个同名的目录,而且它们不为空。所以,我正在寻找类似的东西 shutil.rmtree('directory_*')

有没有办法用Python来做到这一点?

最佳答案

您拥有所有部分:glob() 迭代,rmtree() 删除:

for path in glob.glob("directory_*"):
    shutil.rmtree(path)

如果通配路径之一命名了一个文件,或者由于 rmtree() 可能失败的任何其他原因,这将抛出 OSError。一旦您决定如何处理错误,您就可以根据需要添加错误处理。除非您知道要如何处理错误,否则添加错误处理是没有意义的,因此我将错误处理排除在外。

关于python - python中删除多个目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15653243/

相关文章:

python - 如何在 Python 中使用 Matplotlib 绘制带有数据列表的直方图?

python - Tkinter - Python 3.5

python - 使用 Image Viewer (Eye of GNOME) 在一个目录中打开多个图像

java - 如何使用Java代码将文件夹(包括子目录和文件) move 到新文件夹中

windows - 目录打印工具?

python - shutil.copy2(s,d) 和shutil.move(s,d) 的区别

python - 错误 "filename.whl is not a supported wheel on this platform"

python - GCP/Py : determine when compute engine instance is actually ready to be used (not "RUNNING")

python-3.x - Shutil.make_archive 未压缩到正确的目的地

python - 将zip文件输出到特定目录,而不是脚本目录