more-python/exercises/ex12/rmdir

32 lines
788 B
Python
Executable File

#!/usr/bin/env python
# Exercise 12c
# rmdir command
import sys
import argparse
from pathlib import Path
parser = argparse.ArgumentParser()
parser.add_argument("paths", nargs="+", type=Path)
parser.add_argument("-p", "--parents", action="store_true")
args = parser.parse_args()
error = False
for path in args.paths:
if path.is_file():
print(f"rmdir: fallo al borrar '{path}': No es un directorio")
error = True
elif len(list(path.glob("*"))) > 0:
print(f"rmdir: fallo al borrar '{path}': El directorio no está vacío")
error = True
else:
if args.parents is True:
while len(path.parts) > 0:
path.rmdir()
path = path.parent
else:
path.rmdir()
if error:
sys.exit(1)