歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 使用Python批量刪除文件列表

使用Python批量刪除文件列表

日期:2017/3/1 9:55:22   编辑:Linux編程

環境:
已知要刪除的文件列表,即確定哪些文件要刪除。

代碼如下:

#!/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()
#關閉文件對象

Copyright © Linux教程網 All Rights Reserved