且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在python中删除包含其所有文件的目录?

更新时间:2023-11-28 16:59:16

如果要删除文件

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")