如何在python中删除包含其所有文件的目录? [英] How to remove a directory including all its files in python?

查看:65
本文介绍了如何在python中删除包含其所有文件的目录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一些 Python 代码.我想在程序结束时删除 new_folder 包括它的所有文件.

I'm working on some Python code. I want to remove the new_folder including all its files at the end of program.

有人可以指导我如何做到这一点吗?我见过像 os.rmdir 这样的不同命令,但它只会删除路径.这是我的代码:

Can someone please guide me how I can do that? I have seen different commands like os.rmdir but it only removes the path. Here is my code:

for files in sorted(os.listdir(path)):
  os.system("mv "+path+" new_folder")`

上面的代码会将一个文件夹(称为 check)移动到 new_folder 中.我想从 new_folder 中删除那个检查文件夹.

The code above will move a folder (called check) into new_folder. I want to remove that check folder from the new_folder.

推荐答案

如果要删除文件

import os
os.remove("path_to_file")

但是如果你想删除目录,你不能使用上面的代码删除目录然后使用这个

but you can`t delete directory by using above code if you want to remove directory then use this

import os
os.rmdir("path_to_dir")

从上面的命令,你可以删除一个目录,如果它是空的,如果它不是空的,那么你可以使用shutil模块

from above command, you can delete a directory if it's empty if it's not empty then you can use shutil module

import shutil
shutil.rmtree("path_to_dir")

以上所有方法都是Python方式,如果您知道您的操作系统该方法依赖于操作系统,则以上所有方法都不依赖

All above method are Python way and if you know about your operating system that this method depends on OS all above method is not dependent

import os
os.system("rm -rf _path_to_dir")

这篇关于如何在python中删除包含其所有文件的目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆