先屢一下思路 一步步怎么實現
1 要求是要刪除所有文件(只是刪除文件 而不是文件夾),所以 我們肯定要遍歷這個文件目錄 (for in遍歷)
2 每遍歷一個元素時(文件),我們要判斷該元素的屬性是文件還是文件夾 (os.path.isfile(path))引入os模塊
3 判斷如果是文件,直接刪除;如果是文件夾,繼續遍歷並判斷。 if
代碼:
import os
path =
'D:\\PycharmProjects\\test'
for i in os.listdir(path):
path_file = os.path.join(path,i) // 取文件路徑
if os.path.isfile(path_file):
os.remove(path_file)
else:
for f in os.listdir(path_file):
path_file2 =os.path.join(path_file,f)
if os.path.isfile(path_file2):
os.remove(path_file2)
補充完善:
上面寫的方法還是有缺點的 只能刪除到第二層文件夾 如果第二層文件夾里面還有文件的話 就出來不了了
在此修改下代碼 設計一個方法 然后遞歸去處理:
def del_file(path):
for i in os.listdir(path):
path_file = os.path.join(path,i) // 取文件絕對路徑
if os.path.isfile(path_file):
os.remove(path_file)
else:
del_file(path_file)