파일 시스템을 정기적으로 수동으로 청소하는 것은 좋지 않습니다. 자동화!
파일과 폴더를 수동으로 삭제하는 것은 생각처럼 흥미로운 작업이 아닙니다. 자동화하는 것이 합리적입니다.
우리의 삶을 더 쉽게 만들어줄 파이썬이 여기에 있습니다. Python은 스크립팅을 위한 훌륭한 프로그래밍 언어입니다. 우리는 Python을 활용하여 장애물 없이 작업을 완료할 것입니다. 먼저 Python이 왜 좋은 선택인지 알아야 합니다.
- Python은 작업 자동화에 가장 선호되는 언어입니다.
- 다른 프로그래밍 언어에 비해 적은 코드
- Python은 모든 운영 체제와 호환됩니다. Windows, Linux 및 Mac에서 동일한 코드를 실행할 수 있습니다.
- Python에는 운영 체제와 상호 작용하는 데 도움이 되는 os라는 모듈이 있습니다. 이 모듈을 사용하여 파일 삭제 자동화를 완료합니다.
우리는 Python을 사용하여 성가시거나 반복적인 시스템 작업을 대체할 수 있습니다. 특정 시스템 작업을 완료하기 위한 스크립트를 작성하는 것은 Python을 안다면 컵케이크입니다. 다음 사용 사례를 살펴보겠습니다.
참고: 다음은 Python 3.6 이상에서 테스트되었습니다.
목차
X일이 지난 파일/폴더 제거
종종 오래된 로그는 필요하지 않으며 스토리지를 사용할 수 있도록 정기적으로 정리해야 합니다. 로그뿐만 아니라 무엇이든 될 수 있습니다.
마지막 액세스(st_atime), 수정(st_mtime) 및 메타데이터 수정(st_ctime) 시간에 대한 세부 정보를 제공하는 os 모듈에 stat라는 메서드가 있습니다. 모든 메서드는 Epoch 이후 시간을 초 단위로 반환합니다. 에포크에 대한 자세한 내용은 여기에서 확인할 수 있습니다.
폴더의 하위 폴더를 탐색하기 위해 os.walk(path)라는 메서드를 사용합니다.
날짜 수를 기준으로 삭제 파일/폴더에 대한 코드를 작성하려면 아래 단계를 따르십시오.
- 모듈 가져오기 시간, 운영 체제, 종료
- 변수에 경로와 요일 설정
- time.time() 메서드를 사용하여 일 수를 초로 변환
- os.path.exists(path) 모듈을 사용하여 경로 존재 여부 확인
- 경로가 있으면 하위 폴더를 포함하여 경로에 있는 파일 및 폴더 목록을 가져옵니다. os.walk(path) 메서드를 사용하면 폴더, 파일 및 하위 폴더가 포함된 생성기가 반환됩니다.
- os.path.join() 메서드를 사용하여 현재 경로와 파일/폴더 이름을 모두 결합하여 파일 또는 폴더의 경로를 가져옵니다.
- st_ctime 속성을 사용하여 os.stat(path) 메서드에서 ctime 가져오기
- ctime을 이전에 계산한 시간과 비교합니다.
- 결과가 사용자가 원하는 날짜보다 크면 파일인지 폴더인지 확인합니다. 파일인 경우 os.remove(path)를 사용하고, 그렇지 않으면 shutil.rmtree() 메서드를 사용합니다.
- 경로가 존재하지 않으면 찾을 수 없음 메시지를 인쇄합니다.
코드를 자세히 보자.
# 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()
요구 사항에 따라 위의 코드에서 다음 두 변수를 조정해야 합니다.
days = 30 path = "/PATH_TO_DELETE"
XGB보다 큰 파일 제거
특정 크기보다 큰 파일을 찾아 삭제해 봅시다. 위의 스크립트와 유사합니다. 이전 스크립트에서는 age를 매개변수로 사용했으며 이제 크기를 삭제 매개변수로 사용합니다.
# 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()
다음 두 변수를 조정합니다.
path = "ENTER_PATH_HERE" size = 500
특정 확장자를 가진 파일 제거
확장 유형별로 파일을 삭제하려는 시나리오가 있을 수 있습니다. .log 파일을 가정해 보겠습니다. os.path.splitext(path) 메서드를 사용하여 파일의 확장자를 찾을 수 있습니다. 파일의 경로와 확장자를 포함하는 튜플을 반환합니다.
# 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()
요구 사항을 충족하도록 위 코드의 경로 및 확장 변수를 업데이트하는 것을 잊지 마십시오.
NON PRODUCTION 환경에서 스크립트를 테스트하는 것이 좋습니다. 결과에 만족하면 cron(Linux를 사용하는 경우)을 통해 일정을 예약하여 유지 관리 작업을 위해 주기적으로 실행할 수 있습니다. Python은 이 작업을 수행하는 데 훌륭합니다. 더 많은 작업을 수행하는 방법을 배우고 싶다면 이것을 확인하세요. 유데미 코스.
기사를 재미있게 읽었습니까? 세상과 함께 나누는 건 어떨까요?