Last active
February 5, 2019 18:59
-
-
Save Chaz6/7b01e556c43d379a149b0c44438a2a48 to your computer and use it in GitHub Desktop.
sort-folders-by-largest-file.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/python3.6 | |
import pathlib | |
import shutil | |
import os | |
def filesize(path): | |
return path.stat().st_size | |
def biggest(folder): | |
''' Find the biggest file in folder that matches pattern | |
Search recursively in all subdirectories | |
''' | |
files = [] | |
for f in folder.iterdir(): | |
if f.is_file(): | |
files.append(f) | |
elif f.is_dir(): | |
found = biggest(f) | |
if found: | |
files.append(found) | |
if files: | |
return max(files, key=filesize) | |
def movefolder(root_src_dir,root_dst_dir): | |
for src_dir, dirs, files in os.walk(root_src_dir): | |
dst_dir = src_dir.replace(root_src_dir, root_dst_dir, 1) | |
if not os.path.exists(dst_dir): | |
os.makedirs(dst_dir) | |
for file_ in files: | |
src_file = os.path.join(src_dir, file_) | |
dst_file = os.path.join(dst_dir, file_) | |
if os.path.exists(dst_file): | |
os.remove(src_file) | |
continue | |
shutil.move(src_file, dst_dir) | |
c = pathlib.Path.cwd() | |
for p in c.iterdir(): | |
if(p.name[:9]=="filetype-" or p.is_file()): | |
print(("Ignoring %s" % p.name)) | |
else: | |
try: | |
flag = False | |
largest = biggest(p) | |
if largest: | |
largest_ext = largest.suffix | |
flag = True | |
except OSError: | |
flag = False | |
if flag: | |
print(largest_ext, p.name) | |
d = c / ("filetype-%s" % largest_ext) | |
d.mkdir(exist_ok=True) | |
if pathlib.Path(d / p.name).exists(): | |
movefolder(str(p), str(d / p.name)) | |
shutil.rmtree(str(p)) | |
else: | |
shutil.move(str(p), str(d / p.name)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment