Python Day-to-Day Utility Programs
1. File Backup Script
This script copies all files from a source directory to a backup directory, adding a timestamp to the folder name.
import shutil
import os
from datetime import datetime
def backup_files(source_dir, dest_dir):
# Create a timestamped folder name
timestamp = datetime.now().strftime('%Y-%m-%d_%H-%M-%S')
backup_folder = os.path.join(dest_dir, f"backup_{timestamp}")
try:
shutil.copytree(source_dir, backup_folder)
print(f"Backup successful! Saved to: {backup_folder}")
except Exception as e:
print(f"Backup failed: {e}")
if __name__ == "__main__":
SOURCE = "./important_docs"
DESTINATION = "./backups"
backup_files(SOURCE, DESTINATION)
2. Website Status Checker
This script checks a list of websites to see if they are up (return status code 200).
import requests
websites = [
"https://www.google.com",
"https://www.github.com",
"https://www.nonexistent-website-example.com"
]
def check_status(urls):
for url in urls:
try:
response = requests.get(url, timeout=5)
if response.status_code == 200:
print(f"[UP] {url}")
else:
print(f"[DOWN] {url} (Status: {response.status_code})")
except requests.exceptions.RequestException as e:
print(f"[ERROR] {url} - {e}")
if __name__ == "__main__":
check_status(websites)
3. Log Parser (Find Errors)
This script reads a log file and prints lines containing the word "ERROR".
def parse_logs(log_file):
if not os.path.exists(log_file):
print("Log file not found.")
return
with open(log_file, 'r') as f:
for line_number, line in enumerate(f, 1):
if "ERROR" in line:
print(f"Line {line_number}: {line.strip()}")
if __name__ == "__main__":
parse_logs("application.log")
4. JSON Formatter
This script reads a messy JSON file and saves it as a pretty-printed version.
import json
def format_json(input_file, output_file):
try:
with open(input_file, 'r') as f:
data = json.load(f)
with open(output_file, 'w') as f:
json.dump(data, f, indent=4)
print(f"Formatted JSON saved to {output_file}")
except Exception as e:
print(f"Error: {e}")
if __name__ == "__main__":
format_json("data.json", "data_pretty.json")