python 刪除檔案 夾

2022-06-21 01:24:11 字數 749 閱讀 4844

原文 : 

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:前人栽樹,後人乘涼 

import shutil 

shutil.rmtree()

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

python 刪除資料夾 刪除非空資料夾

一般刪除檔案時使用os庫,然後利用os.remove path 即可完成刪除,如果刪除空資料夾則可使用os.removedirs path 即可,但是如果需要刪除整個資料夾,且資料夾非空時使用os.removedirs path 就會報錯了,此時可以使用shutil庫,該庫為python內建庫,是乙...

Python 刪除檔案 資料夾

import os filepath 需要刪除的檔案路徑 if os.path.exists filepath os.remove filepath else print 該檔案不存在 import os folderpath 需要刪除的資料夾路徑,該資料夾必須為空資料夾 if os.path.ex...

遞迴刪除資料夾 python

遞迴刪除資料夾 def myrmdir dirpath 思路 先將資料夾裡面所有的檔案刪除掉,如果是空資料夾,刪除之,遍歷這個資料夾,得到資料夾下面所有的檔案 filename list os.listdir dirpath print filename list 遍歷這個列表,判斷該元素是檔案還是...