下面來看一下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()