Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

用 Python 批量刪除檔案清單:含備份、統計與錯誤分類

情境很明確:已經有一份「要刪除的檔案清單」,需要批次處理。直接 os.remove 一迴圈風險太高,因此加上備份與分類統計,出問題時能回頭查。

#!/usr/bin/env python
# coding=utf-8
# 目的:依清單刪除檔案,刪前先備份並統計結果
import os
import 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')              # 去掉行尾換行
    if os.path.exists(line):
        if os.path.isfile(line):
            # 把原目錄前綴換成備份目錄前綴
            new_line = line.replace(pre_dir_of_file, backup_dir)
            file_path = os.path.dirname(new_line)
            if not os.path.exists(file_path):
                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()

設計說明

  • 用 os.path.exists → isfile 兩層判斷,把「不存在」與「是目錄」分開統計,避免誤刪目錄。
  • shutil.copy2 而非 copy,會連 metadata(時間戳、權限)一起保留,備份才有意義。
  • 備份路徑透過前綴替換而來,因此清單中的路徑必須與 pre_dir_of_file 前綴一致,否則備份會落到意料之外的位置——實用前請先確認。
  • 正式執行前強烈建議先把 os.remove(line) 註解掉跑一次「乾跑」,確認備份都到位再放行。
  • 此為 Python 2 語法(print 為陳述句);若使用 Python 3,請把 print 改為函式寫法。
Copyright © Linux教程網 All Rights Reserved