Advertisement
Mat4297

DirectoryLister

Mar 27th, 2024 (edited)
699
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.65 KB | Source Code | 0 0
  1. import os
  2. import time
  3. import pathlib
  4. from tqdm import tqdm
  5.  
  6. class DirectoryLister:
  7.  
  8.     def __init__(
  9.         self,
  10.         path,
  11.         reverse=False,
  12.         sort_by="name",
  13.         show_mtime=False,
  14.         show_size=False
  15.     ):
  16.         self.path = path
  17.         self.reverse = reverse
  18.         self.sort_by = sort_by
  19.         if self.sort_by == "name":
  20.             self.output = os.path.basename(self.path) + "\n"
  21.         self.show_mtime, self.show_size = show_mtime, show_size
  22.         self.file_sizes = {}  # Add this line to store file sizes
  23.         self.error_paths = []  # Add this line to store paths that caused errors
  24.         self.total_files = sum([len(files) for r, d, files in os.walk(self.path)])  # Calculate total files
  25.         self.pbar = tqdm(total=self.total_files)  # Initialize tqdm progress bar
  26.  
  27.     def list_directory(
  28.         self,
  29.         indent=0
  30.     ):
  31.         try:
  32.             for root, dirs, files in os.walk(self.path):
  33.  
  34.                 if self.sort_by == "name":
  35.                     dirs.sort()
  36.                 elif self.sort_by == "mtime":
  37.                     dirs.sort(key=lambda dir: os.stat(os.path.join(root, dir)).st_mtime)
  38.                 elif self.sort_by == "size":
  39.                     dirs.sort(key=lambda dir: os.path.getsize(os.path.join(root, dir)))
  40.                 if self.reverse:
  41.                     dirs.reverse()
  42.  
  43.                 for dir in dirs:
  44.                     self.output += f"{'| ' * indent}├─ {dir}\n"
  45.                     self.path=os.path.join(root, dir)
  46.                     self.list_directory(indent + 1)
  47.  
  48.                 if self.sort_by == "name":
  49.                     files.sort()
  50.                 elif self.sort_by == "mtime":
  51.                     files.sort(key=lambda file: os.stat(os.path.join(root, file)).st_mtime)
  52.                 elif self.sort_by == "size":
  53.                     files.sort(key=lambda file: os.path.getsize(os.path.join(root, file)))
  54.                 if self.reverse:
  55.                     files.reverse()
  56.  
  57.                 for file in files:
  58.                     filepath = os.path.join(root, file)
  59.                     if self.show_mtime or self.show_size:
  60.                         stat = os.stat(filepath)
  61.                         mtime = time.strftime(
  62.                             "%Y/%m/%d %H:%M:%S", time.localtime(stat.st_mtime)
  63.                         )
  64.                         size = pathlib.Path(filepath).stat().st_size
  65.                         self.file_sizes[file] = size
  66.                         details = []
  67.                         if self.show_mtime:
  68.                             details.append(f"({mtime})")
  69.                         if self.show_size:
  70.                             details.append(f"({size} bytes)")
  71.                         self.output += f"{'| ' * indent}└─ {file} {' '.join(details)}\n"
  72.                     else:
  73.                         self.output += f"{'| ' * indent}└─ {file}\n"
  74.                     self.pbar.update(1)  # Update the progress bar
  75.         except Exception as e:
  76.             self.output += f"An error occurred while listing the directory: {self.path}\n"
  77.             self.error_paths.append(self.path)
  78.         finally:
  79.             self.pbar.close()  # Close the progress bar
  80.  
  81.     def print_errors(self):
  82.         if self.error_paths:
  83.             self.output += f"\nTotal number of errors: {len(self.error_paths)}\n"
  84.             self.output += "\nErrors occurred at the following paths:\n"
  85.             for path in self.error_paths:
  86.                 self.output += path + "\n"
  87.            
  88.  
  89.     def write_output_to_file(self):
  90.         with open(f"{os.path.basename(self.path)}.txt", "w") as f:
  91.             f.write(self.output)
  92.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement