下面來看一下python裡面是如何刪除一個文件及文件夾的~~
首先引入OS模塊
import os
刪除文件:
os.remove()
刪除空目錄:
os.rmdir()
遞歸刪除空目錄:
os.removedirs()
遞歸刪除目錄和文件(類似DOS命令DeleteTree):
方法1:
# Delete everything reachable from the directory named in 'top',
# assuming there are no symbolic links.
# CAUTION: This is dangerous! For example, if top == '/', it
# could delete all your disk files.
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))
方法2:利用python的成熟的模塊
import shutil
shutil.rmtree()
一行搞定 __import__('shutil').rmtree()