1. os.remove(path)

help:

Remove a file (same as unlink(path)).

删除文件 path. 如果path是一个目录, 抛出 OSError错误。如果要删除目录,请使用rmdir().

remove() 同 unlink() 的功能是一样的

在Windows系统中,删除一个正在使用的文件,将抛出异常。在Unix中,目录表中的记录被删除,但文件的存储还在。

2. os.removedirs(path)

help:

Super-rmdir; remove a leaf directory andall empty intermediate
ones. Works like rmdirexcept that, if the leaf directory issuccessfully removed, directories corresponding to rightmost path
segments will be pruned away until either the whole pathisconsumedoran error occurs. Errors during this latter phase are
ignored-- they generally mean that a directory was not empty.

递归地删除目录。类似于rmdir(), 如果子目录被成功删除, removedirs() 将会删除父目录;但子目录没有成功删除,将抛出错误。

举个例子, os.removedirs(“foo/bar/baz”) 将首先删除 “foo/bar/baz”目录,然后再删除foo/bar 和 foo, 如果他们是空的话

如果子目录不能成功删除,将抛出 OSError异常

3. os.rmdir(path)

help:

Remove a directory.

删除目录 path,要求path必须是个空目录,否则抛出OSError错误

递归删除目录和文件(类似DOS命令DeleteTree):

import os
for root, dirs, files in os.walk(top, topdown=False):
for name in files:
os.remove(os.path.join(root, name))
for name in dirs:
os.rmdir(os.path.join(root, name))

简便方法:前人栽树,后人乘凉

import shutil
shutil.rmtree()

一行搞定 __import__('shutil').rmtree()

4. shutil.rmtree

help:

rmtree(path, ignore_errors=False, οnerrοr=None)
Recursively delete a directory tree.
If ignore_errorsis set, errors are ignored; otherwise, if onerror is set, it is called to handle the error with
arguments (func, path, exc_info) where func is os.listdir, os.remove, or os.rmdir; path is the argument to that
function that caused it to fail; and exc_info is a tuple returned by sys.exc_info(). If ignore_errors is false
and onerror is None, an exception is raised.

例:

目录层级:

/root/test/test1/test2.log
import shutil
shutil.rmtree("/root/test")

結果:/root/test目录不存在了,当然目录test1,文件test2.log也不再存在