Python刪除指定文件夾內指定文件

上次在bilibili上爬了一百多個視頻來當教程,但是它也帶了很多空的彈幕,完全是佔空間,影響視覺,一個一個的刪除是不可能的,還是萬能的代碼好用!

圖例:
在這裏插入圖片描述

1、讀取文件夾中的所有文件

import os
rootdir="F:\數據分析\OpenCV+TensorFlow入門人工智能圖像處理"
filelist=os.listdir(rootdir)
for f in filelist:
    print(f)
OpenCV-TensorFlow 入門人工智能圖像處理 (P1. 1-1 計算機視覺導學_bilibili).cmt.xml
OpenCV-TensorFlow 入門人工智能圖像處理 (P1. 1-1 計算機視覺導學_bilibili).mp4
OpenCV-TensorFlow 入門人工智能圖像處理 (P10. 2-9 像素操作基礎_bilibili).cmt.xml
OpenCV-TensorFlow 入門人工智能圖像處理 (P10. 2-9 像素操作基礎_bilibili).mp4
OpenCV-TensorFlow 入門人工智能圖像處理 (P100. 7-12 knn數字識別10).cmt.xml
OpenCV-TensorFlow 入門人工智能圖像處理 (P100. 7-12 knn數字識別10).mp4
OpenCV-TensorFlow 入門人工智能圖像處理 (P101. 7-13 cnn實現手寫數字識別1).cmt.xml
OpenCV-TensorFlow 入門人工智能圖像處理 (P101. 7-13 cnn實現手寫數字識別1).mp4
OpenCV-TensorFlow 入門人工智能圖像處理 (P102. 7-14 cnn實現手寫數字識別2).cmt.xml
OpenCV-TensorFlow 入門人工智能圖像處理 (P102. 7-14 cnn實現手寫數字識別2).mp4
OpenCV-TensorFlow 入門人工智能圖像處理 (P103. 7-15 cnn實現手寫數字識別3).cmt.xml
OpenCV-TensorFlow 入門人工智能圖像處理 (P103. 7-15 cnn實現手寫數字識別3).mp4
OpenCV-TensorFlow 入門人工智能圖像處理 (P104. 7-16 cnn實現手寫數字識別4).cmt.xml
OpenCV-TensorFlow 入門人工智能圖像處理 (P104. 7-16 cnn實現手寫數字識別4).mp4
......

2、刪除文件

  • 我所要要刪除的文件都是.cmt.xml
import os
rootdir="F:\數據分析\OpenCV+TensorFlow入門人工智能圖像處理"
filelist=os.listdir(rootdir)
for file in filelist:
    if '.cmt.xml' in file:
        del_file = rootdir + '\\' + file #當代碼和要刪除的文件不在同一個文件夾時,必須使用絕對路徑
        os.remove(del_file)#刪除文件
        print("已經刪除:",del_file)
已經刪除: F:\數據分析\OpenCV+TensorFlow入門人工智能圖像處理\OpenCV-TensorFlow 入門人工智能圖像處理 (P1. 1-1 計算機視覺導學_bilibili).cmt.xml
已經刪除: F:\數據分析\OpenCV+TensorFlow入門人工智能圖像處理\OpenCV-TensorFlow 入門人工智能圖像處理 (P10. 2-9 像素操作基礎_bilibili).cmt.xml
已經刪除: F:\數據分析\OpenCV+TensorFlow入門人工智能圖像處理\OpenCV-TensorFlow 入門人工智能圖像處理 (P100. 7-12 knn數字識別10).cmt.xml
已經刪除: F:\數據分析\OpenCV+TensorFlow入門人工智能圖像處理\OpenCV-TensorFlow 入門人工智能圖像處理 (P101. 7-13 cnn實現手寫數字識別1).cmt.xml
已經刪除: F:\數據分析\OpenCV+TensorFlow入門人工智能圖像處理\OpenCV-TensorFlow 入門人工智能圖像處理 (P102. 7-14 cnn實現手寫數字識別2).cmt.xml
已經刪除: F:\數據分析\OpenCV+TensorFlow入門人工智能圖像處理\OpenCV-TensorFlow 入門人工智能圖像處理 (P103. 7-15 cnn實現手寫數字識別3).cmt.xml
......

完美!!!
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章