#!/usr/bin/env python """ This is a program that generates playlists based on the size of the largest file/directory. It searches directories, getting their size and lists the first file in the largest direcotry. """ import os import sys class File: """A file has a size and a name""" def __init__(self, path): self.name = path self.size = os.path.getsize(self.name) def get_size(self): """Get the size of the current file""" return self.size def get_name(self): """Get the name of the current file""" return self.name class Directory: """A directory is a list that can contain files and other directories.""" def __init__(self, path): self.path = path self.files = [] files = os.listdir(path) files.sort() for fil in files: if type(fil).__name__ == "str": self.files.append(File("%s/%s" % (path, fil))) def get_dir_name(self): """Get the name of the current directory.""" return self.path def get_dir_size(self): """Get the size of the current directory.""" ret = 0 for fil in self.files: ret += fil.get_size() return ret def get_head_file(self): """Get the 'head' file in the directory.""" return self.files[0].get_name() def num_files(self): """Get the number of files in the directory.""" return len(self.files) def remove_head_file(self): """Remove the head file from being counted.""" self.files = self.files[1:] def sort_dir(direct): """Sort the directories by size.""" return direct.get_dir_size() def main(): """The main script.""" try: base_dir = sys.argv[1] except IndexError: print "Must enter path of directory to search. Example: %s ./foo" % \ sys.argv[0] os.abort() if os.path.exists(base_dir) == False: print "Could not find path: '%s'" % base_dir os.abort() if base_dir[-1] == "/": base_dir = base_dir[:-1] base_dir_listing = os.listdir(base_dir) directories = [] for direct in base_dir_listing: rel_dir = "%s/%s" % (base_dir, direct) if os.path.islink(rel_dir) == False and os.path.isdir(rel_dir): directories.append(Directory(rel_dir)) while directories: directories.sort(key=sort_dir) directories.reverse() headfile = directories[0].get_head_file() #headfile = headfile.replace('podcasts/', 'podcast/', 1) #print headfile sys.stdout.write("%s\n" % headfile) directories[0].remove_head_file() if directories[0].num_files() == 0: directories = directories[1:] if __name__ == "__main__": main()