Combine `pathlib`, `os`, and `subprocess` to build a log-rotation script that globs for old log files, compresses them into a dated archive with `tar`, and deletes the originals. You will add a `--dry-run` flag, read config from environment variables, and wire everything together with `argparse` ā the same pattern used in real DevOps tooling.
Create the lesson-204 directory, activate the virtual environment, and generate a set of synthetic log files with different ages. You will use `os.utime()` to backdate some files so the rotation logic has real candidates to archive.
mkdir -p ~/devops-python/lesson-204/logs ~/devops-python/lesson-204/archivescd ~/devops-python/lesson-204source ~/devops-python/lesson-101/devops-env/bin/activateimport os
import time
from pathlib import Path
logs_dir = Path('logs')
# Create 6 log files: 3 recent (0ā2 days old) and 3 old (8ā15 days old)
files = [
('app-today.log', 0),
('app-yesterday.log', 1),
('app-2days.log', 2),
('app-8days.log', 8),
('app-10days.log', 10),
('app-15days.log', 15),
]
now = time.time()
for name, days_old in files:
path = logs_dir / name
path.write_text(f'Log content for {name}. Generated for lesson 204.\n' * 5)
# Shift mtime back by days_old days
mtime = now - days_old * 86400
os.utime(path, (mtime, mtime))
print(f'Created {path} ({days_old} days old)')
print(f'\n{len(files)} log files ready in {logs_dir}/')python3 make_sample_logs.pyls -lh logs/os.utime(path, (atime, mtime)) sets the access time and modification time of a file.
Both values are POSIX timestamps (seconds since the Unix epoch).
Subtracting days_old * 86400 from the current time shifts the mtime backward ā 86400 is the number of seconds in a day.
The ls -lh output confirms each file has the expected date.
This technique is useful in tests and automation scripts that need to create realistic file-system state without waiting for real time to pass.
make_sample_logs.py prints six lines showing each file name and its age. ls -lh logs/ shows six files with dates spread across the past 15 days ā the three oldest files show dates 8, 10, and 15 days in the past.