Welcome 微信登录
编程资源 图片资源库 蚂蚁家优选 PDF转换器

首页 / 操作系统 / Linux / 使用Python批量删除文件列表

环境:
已知要删除的文件列表,即确定哪些文件要删除。代码如下:#!/usr/bin/env python
#coding=utf-8
#目的:本程序主要为删除给定的文件列表
import os
import shutil
#引入模块,os为包含普遍的操作系统功能;shutil为文件操作工具的模块
count_not_exist = 0
count_exist_but_dir = 0
count_del_file = 0
backup_dir = "/backup_file/"
pre_dir_of_file = "/var/www/virtualhost/admin.51auto.cn/"
#定义所使用的变量
file_object = open("/tmp/delete.txt")
#打开文件
for line in file_object.readlines():
#读取文件
 line = line.rstrip(" ")
 #去除每行末尾的" "符号
 if os.path.exists(line):
 #判定line文件或目录在系统上存在
     if os.path.isfile(line):
     #判定line为文件
         new_line = line.replace(pre_dir_of_file,backup_dir)
         #替换line中指定目录部分
         file_path = os.path.dirname(new_line)
         #取出new_line文件的目录结构
         if not os.path.exists(file_path):
         #判定new_line文件的目录结构是否存在
             os.makedirs(file_path)
             #其目录不存,创建目录
             print file_path + " :The File Path Create Succeed!"
         shutil.copy2(line,file_path)
         #将文件备份到指定的备份目录
         os.remove(line)
         #删除文件
         count_del_file += 1
     else:
         print line + " :It"s a directory."
         count_exist_but_dir += 1
 else:
     print line + " :The Object is not exists."
     count_not_exist += 1
print str(count_not_exist) + ":The number of objects not exist on the system."
print str(count_exist_but_dir) + " :The number of objects exist,but it"s directory."
print  str(count_del_file) + " :The number of objects deleted in right."
#打印统计变量的值
file_object.close()
#关闭文件对象