import os

filePath = ['/opt']
save = 5
down = 3


def get_dir_path(file_path):
    return [os.path.join(file_path, i) for i in os.listdir(file_path) if os.path.isdir(os.path.join(file_path, i))]


def find_update_path(file_path, down=1):
    for i in range(down):
        file_path += [y for x in file_path for y in get_dir_path(x)]
    return file_path


update_path = find_update_path(filePath, down)
for i in update_path:
    if 'update' in i:
        os.chdir(i)
        clear_list = [x[:-1] for x in os.popen("ls -tl|awk '{print $9}'").readlines() if
                      os.path.isdir(os.path.join(i, x[:-1]))][save:]
        os.system('pwd')
        for x in clear_list:
            os.system('rm -rf %s' % x)
            os.system('ls -hl')

