Рубрики
Без рубрики

Python Script Чтобы удалить файлы старше 1 дня, удалите пустые подсылки рекурсивно и создайте файл журнала для записей!

Кто не любит автоматизировать повторяющиеся ручные задания, верно? Но, возникает вопрос в наших … Tagged с DevOps, Python, Todayered, CodeReview.

Кто не любит автоматизировать повторяющиеся ручные задания, верно? Но в нашем уме появляется вопрос, почему нам нужно автоматизировать этот конкретный процесс удаления файлов и папок! И какая выгода мы получим!

Не волнуйтесь, у меня есть ответ для вас!

Часто необходимо удалить файлы в каталоге, которые старше, чем определенное количество дней. Это особенно в случае с архивными каталогами. Не выполняя текущее обслуживание, эти архивы могут начать потребление большого количества дискового пространства на сервере или на вашем локальном компьютере. Очистка файловой системы регулярно и вручную кажется много времени и больно. Создание сценария для удаления старых архивов делает процесс обслуживания быстро и безболезненно.

Вот питон, чтобы сделать нашу жизнь проще. Python – отличный язык программирования для сценариев. Вы можете использовать тот же код для разных операционных систем I.E. Windows, Linux, Ubuntu или iOS.

В этом процессе автоматизации Мы перечислим все файлы и папки рекурсивно внутри каталога. И среди тех, более старых файлов и пустых подкаталогов также должны быть удалены. Последнее, но не наименее, файл журнала будет создан для хранения записей этого выполнения.

Вот требования, которые нам нужно учитывать первыми:
  1. Создайте сценарий, который будет удалять файлы и дополнительные папки в каталоге рекурсивно, которые старше дня, чем день
  2. Список каждого файла внутри каталога перед удалением и поместите их в файл журнала
  3. Список всех подпапок внутри каталога до удаления и поместите их в файл журнала
  4. Если подпапка имеет недавний файл, не удаляйте папку. Удалите только старые файлы.
  5. Но если подпапка пуста, то удалите подпапку.
  6. Держите записи удаления в файле журнала и сценарии выполнения и время остановки.
  7. Журнал должен быть журналом Rolling, как каждый день, он создает новый журнал с датой (не добавлен к одному файлу журнала)
Давайте расстаться на нашем Todo, чтобы решить эту проблему.
  1. Нам нужно ввести каталог, в котором мы будем запускать наш скрипт
  2. Нам нужно ввести каталог, где мы сохраним наш файл журнала
  3. Создайте файл журнала в данном каталоге (на шаге 2) и назовите его уникально со временем Timestamp.
  4. Внутри данного каталога мы будем искать все файлы и папки рекурсивно.
  5. Получите новейшую дату изменения каждого файла и сравните с предпочтительной датой.
  6. Проверьте, насколько старше файлы есть и если файлы старше одного дня, нам нужно удалить их.
  7. Проверьте, пусты ли подпапки или подкаталоги или нет. Если какая-либо из подпапок пусто, то нам также нужно его удалить.
  8. Наконец, нам нужно сохранить записи всех файлов, папок, некоторых метаданных и устаревших статуса в файле журнала.

Пожалуйста, пройдите все комментарии в скрипту, чтобы понять все шаги там!

# Python 3
import time
import os
from glob import glob, iglob
from pathlib import Path
import glob
import datetime 
from datetime import datetime
import sys


# Directory validation function
def valid_dir(dir):
    #Checking if the path exists or not
    if not os.path.exists(dir):

        #Get current directory where the script has been executed
        cwd = os.getcwd()

        #Create .txt file for log
        f = open(cwd+"/log_createdAt_"+str(datetime.now().timestamp())+".txt",'w')

        #Write in the .txt file
        f.write("* Script execution started at : " + str(currentDate) +"\n"+"\n")
        f.write("This is not a valid path!"+"\n"+"\n")
        f.write("* Script execution stopped at : " + str(currentDate) +"\n"+"\n")
        print("Please provide valid path ")

        #exit
        sys.exit(1)

    #Checking if it is directory or not
    if not os.path.isdir(dir):

        #Get current directory where the script has been executed
        cwd = os.getcwd()

        #Create .txt file for log
        f = open(cwd+"/log_createdAt_"+str(datetime.now().timestamp())+".txt",'w')

        #Write in the .txt file
        f.write("* Script execution started at : " + str(currentDate) +"\n"+"\n")
        f.write("This is not a valid directory path!"+"\n"+"\n")
        f.write("* Script execution stopped at : " + str(currentDate) +"\n"+"\n")
        print("Please provide directory path ")

        #exit
        sys.exit(2)

# Function to convert list into string 
def listToString(s): 

    # initialize an empty string
    str1 = " , " 

    # return string  
    return (str1.join(s))

# Function to list all files and folders recursively inside a directory 
def search_filesNFolders(root_dir,log_dir):

    #Date to compare with file modification date
    compareDate = datetime.today()

    #Iteration integer
    i = 0

    #Create .txt file for log
    f = open(log_dir+"/log_createdAt_"+str(datetime.now().timestamp())+".txt",'w')

    f.write("* Script execution started at : " + str(currentDate) +"\n"+"\n")
    f.write("* Script execution Directory : " + root_dir +"\n")
    f.write("* Log file Directory : " + log_dir+"\n"+"\n")

    f.write("* Date to check with how older the file is : " + str(compareDate)+"\n"+"\n")

    #Loop to search all files and folders in the given directory recursively
    for currentpath, folders, files in os.walk(root_dir):

        #currentpath.replace('\','/')
        f.write("* Current path : "+ currentpath)
        f.write("\n")
        #currentpath.replace('\','/')

        #Iteration integer
        i = 0
        i = i+1

        #Check whether there are any folders in each path or not i.e length of folders list
        #Here there are no folders inside the current directory
        if(len(folders) == 0):

            #Writing the number of files and folders in the log file
            f.write("   Number of Folders : 0"+"\n")
            f.write("   Number of Files: " + str(len(files))+"\n")

            #Check whether there are any files in each folders in the same directory or not i.e length of files list
            if(len(files)==0):

                #Delete the subfolder as it is empty, No files and No folders inside
                os.rmdir(currentpath)

                f.write("   Note: This empty directory has been deleted!"+"\n")
            else:
                f.write("   Filenames: "+"\n")
            print("Folders : 0")

        #Here there are subfolders inside the current directory
        else:
            f.write("   Number of Folders: " + str(len(folders))+"\n")
            f.write("   Foldernames: " + listToString(folders)+"\n")
            f.write("   Number of Files: " + str(len(files))+"\n")

            #If there are files inside the current directory 
            if(len(files)!=0):
                f.write("   Filenames: "+"\n")

            print(folders)

        #Loop to get the metadata and check each file inside current directory
        for file in files:

            #Get the modification time of each file
            t = os.stat(os.path.join(currentpath,file))[8]

            #Check how older the file is from compareDate
            filetime = datetime.fromtimestamp(t) - compareDate
            print(filetime.days)

            #Log the record of file modification date time
            f.write("       "+str(i)+". "+file +"\n"+"          Modifiction date :"+str(datetime.fromtimestamp(t))+"\n"+"          File path : " +currentpath+"/"+file+ "\n")

            i = i+1

            #Check if file is older than 1 day
            if filetime.days < -1:

                #Remove the file
                os.remove(currentpath+"/"+file)

                #Write the delete status in log file
                f.write("       Note: This file has been deleted!"+"\n"+"\n")
                print('Deleted')
            else:
                print('Not older than 1 day!')
            print(file)

        f.write("\n"+"\n")

    #Execution stopped time recorded in log file
    f.write("* Script execution stopped at : " + str(datetime.today().strftime("%Y-%m-%d %H:%M:%S")) +"\n"+"\n")


if __name__=="__main__":

    #Define the directory where you want to run this script
    #root_dir = 'C:/Users/Zeaul.Shuvo/Music/Test'
    root_dir = input("Enter the directory path here for script execution - ")


    #Define the directory where you want to log the records
    #log_dir = 'C:/Users/Zeaul.Shuvo/Music'
    log_dir = input("Enter the directory path here for log file - ")

    #Current date
    currentDate = datetime.today().strftime("%Y-%m-%d %H:%M:%S")

    #Calling the function to validate the root directory
    valid_dir(root_dir)

    #Calling the function to validate the log file directory
    valid_dir(log_dir)

    #Calling the function to search files and folders, delete the older files and empty folders and keep record in log file. 
    search_filesNFolders(root_dir,log_dir)

    #exit
    sys.exit(4)

…..

Помните: нам нужно держать время начала выполнения скрипта и время остановки в файле журнала. В каждом случае нам необходимо сохранить это время записи в файле журнала. Это помогает нам отслеживать активность выполнения скрипта.

Любые вопросы или предложения приветствуются. Ожидание ваших ценных слов! Спасибо!

Оригинал: “https://dev.to/shuvohoque/python-script-to-delete-files-older-than-1-day-delete-empty-sub-directories-recursively-and-create-a-log-file-for-records-3p38”