Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import os
- import time
- import pathlib
- from tqdm import tqdm
- class DirectoryLister:
- def __init__(
- self,
- path,
- reverse=False,
- sort_by="name",
- show_mtime=False,
- show_size=False
- ):
- self.path = path
- self.reverse = reverse
- self.sort_by = sort_by
- if self.sort_by == "name":
- self.output = os.path.basename(self.path) + "\n"
- self.show_mtime, self.show_size = show_mtime, show_size
- self.file_sizes = {} # Add this line to store file sizes
- self.error_paths = [] # Add this line to store paths that caused errors
- self.total_files = sum([len(files) for r, d, files in os.walk(self.path)]) # Calculate total files
- self.pbar = tqdm(total=self.total_files) # Initialize tqdm progress bar
- def list_directory(
- self,
- indent=0
- ):
- try:
- for root, dirs, files in os.walk(self.path):
- if self.sort_by == "name":
- dirs.sort()
- elif self.sort_by == "mtime":
- dirs.sort(key=lambda dir: os.stat(os.path.join(root, dir)).st_mtime)
- elif self.sort_by == "size":
- dirs.sort(key=lambda dir: os.path.getsize(os.path.join(root, dir)))
- if self.reverse:
- dirs.reverse()
- for dir in dirs:
- self.output += f"{'| ' * indent}├─ {dir}\n"
- self.path=os.path.join(root, dir)
- self.list_directory(indent + 1)
- if self.sort_by == "name":
- files.sort()
- elif self.sort_by == "mtime":
- files.sort(key=lambda file: os.stat(os.path.join(root, file)).st_mtime)
- elif self.sort_by == "size":
- files.sort(key=lambda file: os.path.getsize(os.path.join(root, file)))
- if self.reverse:
- files.reverse()
- for file in files:
- filepath = os.path.join(root, file)
- if self.show_mtime or self.show_size:
- stat = os.stat(filepath)
- mtime = time.strftime(
- "%Y/%m/%d %H:%M:%S", time.localtime(stat.st_mtime)
- )
- size = pathlib.Path(filepath).stat().st_size
- self.file_sizes[file] = size
- details = []
- if self.show_mtime:
- details.append(f"({mtime})")
- if self.show_size:
- details.append(f"({size} bytes)")
- self.output += f"{'| ' * indent}└─ {file} {' '.join(details)}\n"
- else:
- self.output += f"{'| ' * indent}└─ {file}\n"
- self.pbar.update(1) # Update the progress bar
- except Exception as e:
- self.output += f"An error occurred while listing the directory: {self.path}\n"
- self.error_paths.append(self.path)
- finally:
- self.pbar.close() # Close the progress bar
- def print_errors(self):
- if self.error_paths:
- self.output += f"\nTotal number of errors: {len(self.error_paths)}\n"
- self.output += "\nErrors occurred at the following paths:\n"
- for path in self.error_paths:
- self.output += path + "\n"
- def write_output_to_file(self):
- with open(f"{os.path.basename(self.path)}.txt", "w") as f:
- f.write(self.output)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement