先上程序:
import os
def Type_File_Delete(file_path, file_type):
all_files = os.listdir(file_path)
for file in all_files:
if file.endswith(file_type):
path_typeFile = os.path.join(file_path, file)#获取文件的完整路径
if os.path.exists(path_typeFile):
os.remove(path_typeFile)
详解:
1)采用files=os.listdir(file_path)获取指定路径下的所有文件;
2)for file in files,采用for循环逐个文件判断;
3)if file.endswitch(file_type),判断文件的尾缀是否是指定类型的文件,若是则返回True,否则返回False;
4)path_typeFile = os.path.join(file_path, file),表示合成并获取文件的完整路径;
5)if os.path.exists(path_typeFile),判断文件是否存在;
6)os.remove(path_typeFile),表示删除文件;
应用方法:
file_path = "F:/Code"
file_type = ".bin"
Type_File_Delete(file_path, file_type)
执行上述命令,则会删除指定目录下的所有bin文件。