Created
October 14, 2019 17:33
-
-
Save liquidgenius/7758dd485cdf390875118bcecfd34102 to your computer and use it in GitHub Desktop.
A Python function using Pathlib that checks for all files in a given directory and if the creation day of a file is greater than a specified number of days into the past and deletes the file if it has expired.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
from pathlib import Path | |
def remove_expired_files(file_path, expiry_days=60, use_UTC=False): | |
""" Checks if the creation day of a file is greater than the file_expiry_days and deletes it if it is. | |
:param file_path: Pathlib.Path: The path to a file | |
:param expiry_days: int: Age in days after which the file should be deleted | |
:param use_UTC: bool: Flag to determine if now should be in UTC time, defaults to False. | |
:return: None | |
""" | |
# set the current datetime based on use_UTC flag | |
if not use_UTC: | |
now = datetime.now() | |
else: | |
now = datetime.utcnow() | |
# determine file age in days | |
age = (now - datetime.fromtimestamp(file_path.stat().st_ctime)).days | |
# delete the file if it is aged past expiry | |
file_path.unlink() if age > expiry_days else None | |
return None | |
# generate the filepath to logs folder using the current working directory | |
logs_path = Path.cwd() / 'logs' | |
# remove expired files in logs folder using a comprehension | |
[remove_expired_files(file) for file in logs_path.glob('*.log')] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment