Advertisement
teslariu

comando dir

Oct 14th, 2023
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. """
  4. Script que suimula el comando dir en Windows
  5.  
  6. requisito:instalar tabulate: pip install tabulate
  7. """
  8.  
  9. import os
  10. from datetime import datetime
  11. from tabulate import tabulate
  12.  
  13. # creo una tabla para mostrar los datos
  14. # formato de la tabla
  15. # si es un archivo
  16. # <fecha y hora> <tamaño> <nombre>
  17. # si es un dir
  18. # <fecha y hora> <DIR> <nombre>
  19.  
  20. archivos = 0
  21. directorios = 0
  22. tabla = []
  23.  
  24. # Escaneo el directorio y leo los datos
  25. for entrada in os.scandir(os.getcwd()):
  26. # leo la información del archivo/directorio
  27. info = entrada.stat()
  28.  
  29. # almaceno su nombre
  30. nombre = entrada.name
  31.  
  32. # leo fecha y hora
  33. fecha_y_hora = datetime.utcfromtimestamp(info.st_mtime).strftime("%d/%m/%Y %H:%M")
  34.  
  35. if entrada.is_file():
  36. archivos += 1
  37.  
  38.  
  39. # leo el tamaño del archivo en Bytes
  40. tam = info.st_size
  41. if tam < 1024:
  42. tam = f"{tam}B"
  43.  
  44. elif 1024 <= tam < 1024**2:
  45. tam = f"{tam/1024:.1f}KB"
  46.  
  47. else:
  48. tam = f"{tam/1024**2:.1f}MB"
  49.  
  50. # agrego el dato a la tabla
  51. tabla.append([fecha_y_hora, "", tam, nombre])
  52.  
  53. elif entrada.is_dir():
  54. directorios += 1
  55.  
  56. # agrego el dato a la tabla
  57. tabla.append([fecha_y_hora, "<DIR>", "", nombre])
  58.  
  59. else:
  60. # agrego el dato a la tabla
  61. tabla.append(fecha_y_hora, "-----", "-----", nombre)
  62.  
  63. print(tabulate(
  64. tabla,
  65. tablefmt = "plain",
  66. colalign = ["center", "center", "right", "left"]
  67. )
  68. )
  69. print(f"{archivos} archivos".center(80))
  70. print(f"{directorios} directorios")
  71.  
  72.  
  73.  
  74.  
  75.  
  76.  
  77.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement