Python – Getting an Excel List of all Folders and Files in them

Getting a list of all folders within a given folder is actually a single line command. Writing it to Excel is usually another line. Getting all files, within these folders is not a lot as well.

However, having a tool that actually does all these is a bit of coding. Hence, I have decided to do it and even to make a YouTube video about it.

A monument in Bulgaria, for the 1885 war.

So, this is what the code does:

  1. Collects Folder Paths and Names: The code identifies all folders within a given directory (path) and creates lists of their paths and names. If include_root is set to True, the root directory itself is also included in these lists.
  2. Builds a File Dictionary: It then creates a dictionary (file_dict) where each folder name is a key, and the values are lists of file names in each corresponding folder. If full_name is False, only the file names (without extensions) are stored.
  3. Pads File Lists for Uniform Length: To ensure all folders have the same number of entries in the dictionary, the code finds the maximum number of files in any folder and pads shorter lists with empty strings.
  4. Creates a DataFrame: The code converts the dictionary into a Pandas DataFrame, with each folder name as a column and each row representing files (or empty entries) from each folder.
  5. Saves to Excel: Finally, the DataFrame is saved as an Excel file named files_in_all_folders.xlsx, and the path to this Excel file is returned.

As simple as that. It is even present in YouTube here:

The code is below:

Enjoy it! 🙂

Tagged with: , , , ,