Advertisement
teslariu

dir en Python

Aug 22nd, 2023
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.46 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. import os
  5. from datetime import datetime
  6. from tabulate import tabulate
  7.  
  8. archivos = 0
  9. directorios = 0
  10.  
  11. # Creo una tabla para agregar los datos
  12. # formato de la tabla
  13. # si es un archivo:
  14. # <fecha y hora> <tamaño> <nombre>
  15. # Si es un directorio
  16. # <fecha y hora> <DIR> <nombre>
  17. tabla = []
  18.  
  19. # Escaneo el directorio y leo los datos diferenciando si es file or dir
  20. for entrada in os.scandir(os.getcwd()):
  21. nombre = entrada.name
  22. timestamp = entrada.stat().st_mtime
  23. fecha_y_hora = datetime.utcfromtimestamp(timestamp).strftime("%d/%m/%Y %H:%M")
  24.  
  25. if entrada.is_file():
  26. archivos += 1
  27.  
  28. # leo la info del objeto 'entrada'
  29. info = entrada.stat()
  30.  
  31. # leo el tamaño del archivo
  32. size = info.st_size
  33.  
  34. # formateo el tamaño en B, Kb, Mb
  35. if size < 1024:
  36. size = f"{size:.1f} B"
  37.  
  38. elif 1024 <= size <= 1024**2:
  39. size = f"{size/1024:.1f} KB"
  40.  
  41. else:
  42. size = f"{size/1024**2:.1f} MB"
  43.  
  44. # agrego una fila en la tabla
  45. tabla.append([fecha_y_hora, "", size, nombre])
  46.  
  47.  
  48. elif entrada.is_dir():
  49. directorios += 1
  50. # agrego una fila a la tabla
  51. tabla.append([fecha_y_hora, "<DIR>", "", nombre])
  52.  
  53. else:
  54. tabla.append(["----", "----", "----", "----"])
  55.  
  56. print(tabulate(
  57. tabla,
  58. tablefmt = "plain",
  59. colalign = ['center', 'center', 'right', 'left']
  60. )
  61. )
  62.  
  63. print(f"\n\n{archivos} archivos")
  64. print(f"{directorios} directorios")
  65.  
  66.  
  67.  
  68.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement