teslariu

dir con python

Jul 4th, 2023
1,152
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 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  # biblioteca externa, pip install tabulate para instalarla
  7.  
  8.  
  9. archivos = 0
  10. directorios = 0
  11.  
  12. # creo la tabla vacia
  13. # formato de la tabla
  14. # si es un archivo:    <fecha y hora>       <tamaño> <nombre>
  15. # si es un directorio: <fecha y hora>  DIR           <nombre>
  16. tabla = []
  17.  
  18. # escaneo el directorio y leo los datos
  19. for item in os.scandir(os.getcwd()):
  20.     if item.is_file():
  21.         archivos += 1
  22.         nombre = item.name
  23.        
  24.         # leo la info del archivo
  25.         info = item.stat()
  26.        
  27.         # leo el tamaño del archivo
  28.         tam = info.st_size
  29.        
  30.         # doy formato al tamaño:
  31.         if tam < 1024:
  32.             tam = f"{tam} B"
  33.        
  34.         elif 1024 <= tam <1024**2:
  35.             tam = f"{tam/1024:.1f} KB"
  36.            
  37.         else:
  38.             tam = f"{tam/1024**2:.1f} MB"
  39.        
  40.         # leo fecha y hora del ultima modificacion
  41.         modif = datetime.utcfromtimestamp(info.st_mtime).strftime('%d/%m/%Y %H:%M')
  42.        
  43.         # agrego el dato a la tabla
  44.         tabla.append([modif,"",tam,nombre])
  45.        
  46.        
  47.     elif item.is_dir():
  48.         directorios += 1
  49.         nombre = item.name
  50.        
  51.         # leo fecha y hora del ultima modificacion
  52.         modif = datetime.utcfromtimestamp(info.st_mtime).strftime('%d/%m/%Y %H:%M')
  53.        
  54.         # agrego el dato a la tabla
  55.         tabla.append([modif,"<DIR>","",nombre])
  56.  
  57. print(f"Directorio: {os.getcwd()}\n")
  58.  
  59. print(tabulate(
  60.         tabla,
  61.         tablefmt = "plain",
  62.         colalign = ["center","center", "right", "left"],
  63.     )
  64. )
  65.            
  66. print(f"\n\n\t\t{archivos} archivos")
  67. print(f"\t\t{directorios} directorios")        
  68.        
  69.            
  70.            
  71.        
  72.        
  73.        
  74.        
  75.        
  76.  
Advertisement
Add Comment
Please, Sign In to add comment