I have a folder system with the structure below:
folderA
- folder1
- file1A.txt
- folder2
- file2A.txt
- folder3
- file3A.txt
folderB
- folder1
- file1B.txt
- folder2
- file2B.txt
- folder3
- file3B.txt
I wish to change the order to make the numbered folder above the letter folders as:
folder1
- folderA
- file1A.txt
- folderB
- file1B.txt
folder2
- folderA
- file2A.txt
- folderB
- file2B.txt
folder3
- folderA
- file3A.txt
- folderB
- file3B.txt
Here is a piece of code to construct a MWE of the initial directory structure:
import os
import shutil
import string
root_dir = os.getcwd()
os.chdir('/home/alletro/Tc-97/tools')
os.makedirs('master', exist_ok=True)
os.chdir('master')
master_dir = os.getcwd()
top_tier = [f'folder{i}' for i in range(1,4)]
second_tier = [f'folder{i}' for i in list(string.ascii_uppercase)[:4]]
for folder in top_tier:
os.chdir(master_dir)
os.makedirs(folder, exist_ok=True)
os.chdir(folder)
fold_dir = os.getcwd()
for sub_folder in second_tier:
os.chdir(fold_dir)
os.makedirs(sub_folder, exist_ok=True)
os.chdir(sub_folder)
os.mknod("newfile.txt")
os.chdir(root_dir)
I have found a solution that gets me a dictionary of the directory tree:
def get_directory_structure(rootdir):
"""
Creates a nested dictionary that represents the folder structure of rootdir
"""
dir = {}
rootdir = rootdir.rstrip(os.sep)
start = rootdir.rfind(os.sep) + 1
for path, dirs, files in os.walk(rootdir):
folders = path[start:].split(os.sep)
subdir = dict.fromkeys(files)
parent = reduce(dict.get, folders[:-1], dir)
parent[folders[-1]] = subdir
return dir
I'm however struggling to see where to take it from here.