Friday, December 18, 2020

Group files by folders in Python

 I sometimes need to display a list of files coming in this format:

folder1/file1

folder2/file1

folder1/file2 ...

 And I want to display it in this format:

folder1

file1

file2

folder2

 file1

 Here is my code. It uses the groupby function from the itertools library:

from itertools import groupby

def format_files_by_folder(folder,filenames):
    return folder + "\n  " + "\n  ".join([f[1for f in filenames])

def file_by_folder(file_list):
    files_and_folders = [(f.split('/')[0], '/'.join(f.split('/')[1:])) 
        for f in file_list]

    # Group by folder
    files_and_folders.sort(key=lambda f: f[0])
    files_by_folder = groupby(files_and_folders, lambda f: f[0])

    return "\n\n".join(
        [format_files_by_folder(folder, filenames) 
            for folder, filenames in files_by_folder])