如何在python中删除包含其所有文件的目录?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/43756284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to remove a directory including all its files in python?
提问by sara
I'm working on some Python code. I want to remove the new_folder
including all its files at the end of program.
我正在处理一些 Python 代码。我想new_folder
在程序结束时删除包括它的所有文件。
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:
有人可以指导我如何做到这一点吗?我见过像 os.rmdir 这样的不同命令,但它只会删除路径。这是我的代码:
for files in sorted(os.listdir(path)):
os.system("mv "+path+" 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.
上面的代码会将一个文件夹(称为 check)移动到 new_folder 中。我想从 new_folder 中删除那个检查文件夹。
回答by Kallz
If you want to delete the file
如果要删除文件
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")
from above command, you can delete a directory if it's empty if it's not empty then you can use shutil module
从上面的命令,你可以删除一个目录,如果它是空的,如果它不是空的,那么你可以使用shutil模块
import shutil
shutil.rmtree("path_to_dir")
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
以上所有方法都是 Python 方式,如果您了解您的操作系统,该方法依赖于操作系统,则以上所有方法都不依赖
import os
os.system("rm -rf _path_to_dir")
回答by Netwave
回答by PMonti
use os.system("rm -rf" + whatever_path +" new_folder")
用 os.system("rm -rf" + whatever_path +" new_folder")