The issue I have with this class is that most of the methods are almost the same. I would like for this code to be more pythonic.
Note: I plan on replacing all the for
loop constructs with list comprehensions.
class Sorter(BaseCrawler):
def __init__(self, base_dir):
self.base_dir = base_dir
def by_size(self, *options):
'''
Sort files by size
'''
file_list = []
for fn in self.files(*options):
file_list.append((fn, float(os.path.getsize(fn))))
file_list.sort(key=lambda fn: fn[1])
return file_list
def by_mtime(self, *options):
'''
Sort files by modified time.
'''
file_list = []
for fn in self.files(*options):
file_list.append((fn, os.path.getmtime(fn)))
file_list.sort(key=lambda fn: fn[1])
return file_list
def by_ctime(self, *options):
'''
Sort files by creation time.
'''
file_list = []
for fn in self.files(*options):
file_list.append((fn, os.path.getctime(fn)))
file_list.sort(key=lambda fn: fn[1])
return file_list
def by_atime(self, *options):
'''
Sort files by access time.
'''
file_list = []
for fn in self.files(*options):
file_list.append((fn, os.path.getatime(fn)))
file_list.sort(key=lambda fn: fn[1])
return file_list
def last_modified(self):
'''
Return the last modified file.
'''
return self.by_mtime()[0]
def last_accessed(self):
'''
Return the last accessed file.
'''
return self.by_atime()[0]
def last_created(self):
'''
Return the last created file.
'''
return self.by_ctime()[0]
def average_fsize(self):
'''
Return the average file size.
'''
sizes = []
for name, size in c.by_size():
sizes.append(size)
return sum(sizes) / len(sizes)
def above_avg_size(self, times):
'''
Yield files that have an above average file size.
'''
avg = self.average_fsize()
for f, s in c.by_size():
if s > avg * times:
yield f, s