手机版
你好,游客 登录 注册 搜索
背景:
阅读新闻

使用Python批量删除文件列表

[日期:2013-07-06] 来源:Linux社区  作者:lgdvsehome [字体:大 中 小]

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

代码如下:

#!/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('\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()
#关闭文件对象

linux
相关资讯       python 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款