python列表删除算法_使用Python批量删除文件列表

使用Python批量删除文件列表

环境:

已知要删除的文件列表,即确定哪些文件要删除。

代码如下:

#!/usr/bin/env python

#coding=utf-8

#目的:本程序主要为删除给定的文件列表

import os

import shutil#引入模块,os为包含普遍的操作系统功能;shutil为文件操作工具的模块

count_not_exist = 0

count_exist_but_dir = 0count_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(‘\n’)

#去除每行末尾的’\n’符号

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()

#关闭文件对象

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值