在進(jìn)行實(shí)驗(yàn)時(shí),總會(huì)遇到想刪除文件,但文件太多了,一個(gè)一個(gè)去刪,費(fèi)時(shí)費(fèi)力費(fèi)眼睛,因此想到用程序來自動(dòng)去刪。 使用程序來刪文件可以有很多方式。
本文的代碼僅記錄的是根據(jù)某種后綴移動(dòng)文件到另一個(gè)文件夾。 移動(dòng)之后,原文件夾里就沒有此文件了。 import os import shutil #根據(jù)文件后綴將其移動(dòng)到另一個(gè)文件夾,原文件夾里沒有此文件了 #path是原文件夾路徑 #new_path是新文件夾路徑 #type是要移動(dòng)的文件類型 def move_file(path, new_path, type): file_path = os.listdir(path) #以列表形式返回path中的所有文件 # print(file) # print(len(file)) count = 0 for file in file_path: filepath = path + "\\" + file #文件的路徑 # print(filepath + "\n") # print(file[-5:]) length = len(type) if file[-length:] == type: print(filepath + "\n") shutil.move(filepath, new_path) count = count + 1 print(path + "文件夾中總共移動(dòng)了 " + str(count) + " 個(gè)文件 ---> " + new_path) 測(cè)試代碼如下: path = r"E:\yolo\labels" new_path = r"E:\yolo\label" type = '.txt' move_file(path, new_path, type) 通過測(cè)試前后的文件夾中的文件情況,可驗(yàn)證代碼是否成功。
|