Look for file and folder created yesterday
The python script below gets the newest file and directory created yesterday. The file and directory must match a pattern.
The file and directory are then zipped. The source file and directory remain on the drive.
import os
import datetime
import re
import shutil
import tarfile
def get_newest_in_previous_day(path):
previous_day_files = []
previous_day_dirs = []
previous_day = (datetime.datetime.now() - datetime.timedelta(days=1))
pattern = re.compile(r"\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z(\.pbm\.json)?$")
for name in os.listdir(path):
# Skip names that do not match the pattern
if not pattern.match(name):
continue
full_path = os.path.join(path, name)
timestamp_str = name.split('T')[0] # Extract the date part from the name
timestamp = datetime.datetime.strptime(timestamp_str, "%Y-%m-%d")
# Check if it's the previous day
if timestamp.date() == previous_day.date():
if os.path.isfile(full_path):
previous_day_files.append((timestamp, name))
elif os.path.isdir(full_path):
previous_day_dirs.append((timestamp, name))
# Sort by timestamp (newest first) and get the first name
previous_day_files.sort(reverse=True)
previous_day_dirs.sort(reverse=True)
newest_file = previous_day_files[0][1] if previous_day_files else None
newest_dir = previous_day_dirs[0][1] if previous_day_dirs else None
gzip_name = previous_day.strftime("%Y-%m-%d-Database.gzip")
gzip_file_path = os.path.join(path, gzip_name)
# If both the file and directory exist, compress them
if newest_file and newest_dir:
with tarfile.open(gzip_file_path, "w:gz") as tar:
tar.add(os.path.join(path, newest_file))
tar.add(os.path.join(path, newest_dir))
print("File and directory were zipped.")
else:
print("Nothing was zipped.")
return newest_file, newest_dir
path = "/mnt/backups/0300/rs"
get_newest_in_previous_day(path)