automate-boring-stuff/exercises/ex10/ex10a.py

40 lines
1.2 KiB
Python

"""
Project: Selective Copy
Page 247
"""
import sys
import shutil
import argparse
from pathlib import Path
parser = argparse.ArgumentParser(description='Copia selectiva')
parser.add_argument("-e", "--ext", type=str, default='*')
parser.add_argument("-i", "--input", type=Path, default=Path.cwd())
parser.add_argument("-o", "--output", type=Path, required=True)
parser.add_argument("-f", "--force", action="store_true")
args = parser.parse_args()
if not args.input.exists():
print("ERROR: el input no existe")
sys.exit(1)
if args.output.is_file():
print("ERROR: el output es un archivo existente")
sys.exit(1)
if not args.output.exists():
args.output.mkdir()
extension = args.ext[0] != "." and f"*.{args.ext}" or f"*{args.ext}"
for file in list(args.input.glob(f"**/{extension}")):
new_path = args.output / file.name
if len(set(file.parents) - set(args.output.resolve().parents)) == 0:
if new_path.exists() and not args.force:
print(f"WARN: {new_path} ya existe; no se copió")
elif new_path.exists() and args.force:
print(f"WARN: {new_path} ya existe; sobreescribiendo")
shutil.copy2(file, new_path)
else:
shutil.copy2(file, new_path)