Limpar o sistema de arquivos regularmente manualmente não é bom. Automatize-os!
Excluir arquivos e pastas manualmente não é uma tarefa empolgante, como se pode pensar. Faz sentido automatizá-los.
Aí vem o Python para facilitar nossas vidas. Python é uma excelente linguagem de programação para scripts. Vamos aproveitar o Python para terminar nossa tarefa sem nenhum obstáculo. Primeiro, você deve saber por que o Python é uma boa escolha.
- Python é uma linguagem favorita de todos os tempos para automatizar tarefas
- Menos código em comparação com outras linguagens de programação
- Python é compatível com todos os sistemas operacionais. Você pode executar o mesmo código no Windows, Linux e Mac.
- Python tem um módulo chamado os que nos ajuda a interagir com o sistema operacional. Vamos usar este módulo para completar nossa automação de excluir os arquivos.
Podemos substituir qualquer tarefa de sistema irritante ou repetitiva usando Python. Escrever scripts para completar uma tarefa específica do sistema é um bolinho se você conhece Python. Vejamos o seguinte caso de uso.
Nota: os itens a seguir são testados no Python 3.6+
últimas postagens
Removendo arquivos/pastas com mais de X dias
Muitas vezes, você não precisa de logs antigos e precisa limpá-los regularmente para disponibilizar o armazenamento. Pode ser qualquer coisa e não apenas logs.
Temos um método chamado stat no módulo os que fornece detalhes da hora do último acesso (st_atime), modificação (st_mtime) e modificação de metadados (st_ctime). Todos os métodos retornam o tempo em segundos desde a época. Você pode encontrar mais detalhes sobre a época aqui.
Usaremos um método chamado os.walk(path) para percorrer as subpastas de uma pasta.
Siga as etapas abaixo para escrever o código para os arquivos/pastas de exclusão com base no número de dias.
- Importe os módulos time, os, shutil
- Defina o caminho e os dias para as variáveis
- Converta o número de dias em segundos usando o método time.time()
- Verifique se o caminho existe ou não usando o módulo os.path.exists(path)
- Se o caminho existir, obtenha a lista de arquivos e pastas presentes no caminho, incluindo subpastas. Use o método os.walk(path), e ele retornará um gerador contendo pastas, arquivos e subpastas
- Obtenha o caminho do arquivo ou pasta juntando o caminho atual e o nome do arquivo/pasta usando o método os.path.join()
- Obtenha o ctime do método os.stat(path) usando o atributo st_ctime
- Compare o ctime com o tempo que calculamos anteriormente
- Se o resultado for maior que os dias desejados do usuário, verifique se é um arquivo ou pasta. Se for um arquivo, use o os.remove(path) senão use o método shutil.rmtree()
- Se o caminho não existir, imprimir mensagem não encontrada
Vamos ver o código em detalhes.
# importing the required modules import os import shutil import time # main function def main(): # initializing the count deleted_folders_count = 0 deleted_files_count = 0 # specify the path path = "/PATH_TO_DELETE" # specify the days days = 30 # converting days to seconds # time.time() returns current time in seconds seconds = time.time() - (days * 24 * 60 * 60) # checking whether the file is present in path or not if os.path.exists(path): # iterating over each and every folder and file in the path for root_folder, folders, files in os.walk(path): # comparing the days if seconds >= get_file_or_folder_age(root_folder): # removing the folder remove_folder(root_folder) deleted_folders_count += 1 # incrementing count # breaking after removing the root_folder break else: # checking folder from the root_folder for folder in folders: # folder path folder_path = os.path.join(root_folder, folder) # comparing with the days if seconds >= get_file_or_folder_age(folder_path): # invoking the remove_folder function remove_folder(folder_path) deleted_folders_count += 1 # incrementing count # checking the current directory files for file in files: # file path file_path = os.path.join(root_folder, file) # comparing the days if seconds >= get_file_or_folder_age(file_path): # invoking the remove_file function remove_file(file_path) deleted_files_count += 1 # incrementing count else: # if the path is not a directory # comparing with the days if seconds >= get_file_or_folder_age(path): # invoking the file remove_file(path) deleted_files_count += 1 # incrementing count else: # file/folder is not found print(f'"{path}" is not found') deleted_files_count += 1 # incrementing count print(f"Total folders deleted: {deleted_folders_count}") print(f"Total files deleted: {deleted_files_count}") def remove_folder(path): # removing the folder if not shutil.rmtree(path): # success message print(f"{path} is removed successfully") else: # failure message print(f"Unable to delete the {path}") def remove_file(path): # removing the file if not os.remove(path): # success message print(f"{path} is removed successfully") else: # failure message print(f"Unable to delete the {path}") def get_file_or_folder_age(path): # getting ctime of the file/folder # time will be in seconds ctime = os.stat(path).st_ctime # returning the time return ctime if __name__ == '__main__': main()
Você precisa ajustar as duas variáveis a seguir no código acima com base no requisito.
days = 30 path = "/PATH_TO_DELETE"
Removendo arquivos maiores que X GB
Vamos procurar os arquivos maiores que um determinado tamanho e excluí-los. É semelhante ao script acima. No script anterior, tomamos a idade como parâmetro e agora usaremos o tamanho como parâmetro para a exclusão.
# importing the os module import os # function that returns size of a file def get_file_size(path): # getting file size in bytes size = os.path.getsize(path) # returning the size of the file return size # function to delete a file def remove_file(path): # deleting the file if not os.remove(path): # success print(f"{path} is deleted successfully") else: # error print(f"Unable to delete the {path}") def main(): # specify the path path = "ENTER_PATH_HERE" # put max size of file in MBs size = 500 # checking whether the path exists or not if os.path.exists(path): # converting size to bytes size = size * 1024 * 1024 # traversing through the subfolders for root_folder, folders, files in os.walk(path): # iterating over the files list for file in files: # getting file path file_path = os.path.join(root_folder, file) # checking the file size if get_file_size(file_path) >= size: # invoking the remove_file function remove_file(file_path) else: # checking only if the path is file if os.path.isfile(path): # path is not a dir # checking the file directly if get_file_size(path) >= size: # invoking the remove_file function remove_file(path) else: # path doesn't exist print(f"{path} doesn't exist") if __name__ == '__main__': main()
Ajuste as duas variáveis a seguir.
path = "ENTER_PATH_HERE" size = 500
Removendo arquivos com uma extensão específica
Pode haver um cenário em que você deseja excluir arquivos por seus tipos de extensão. Digamos arquivo .log. Podemos encontrar a extensão de um arquivo usando o método os.path.splitext(path). Ele retorna uma tupla contendo o caminho e a extensão do arquivo.
# importing os module import os # main function def main(): # specify the path path = "PATH_TO_LOOK_FOR" # specify the extension extension = ".log" # checking whether the path exist or not if os.path.exists(path): # check whether the path is directory or not if os.path.isdir(path): # iterating through the subfolders for root_folder, folders, files in os.walk(path): # checking of the files for file in files: # file path file_path = os.path.join(root_folder, file) # extracting the extension from the filename file_extension = os.path.splitext(file_path)[1] # checking the file_extension if extension == file_extension: # deleting the file if not os.remove(file_path): # success message print(f"{file_path} deleted successfully") else: # failure message print(f"Unable to delete the {file_path}") else: # path is not a directory print(f"{path} is not a directory") else: # path doen't exist print(f"{path} doesn't exist") if __name__ == '__main__': # invoking main function main()
Não se esqueça de atualizar o caminho e a variável de extensão no código acima para atender aos seus requisitos.
Sugiro testar os scripts no ambiente NON PRODUCTION. Quando estiver satisfeito com os resultados, você pode agendar por meio do cron (se estiver usando Linux) para executá-lo periodicamente para trabalhos de manutenção. Python é ótimo para conseguir essas coisas e se estiver interessado em aprender a fazer mais, confira isso Curso Udemy.
Gostou de ler o artigo? Que tal compartilhar com o mundo?