Reputation: 21
sorry for the simple question, but i dont know how to solve my easy problem. I would like to create a folder tree. I am selecting the main folder and create the first level of subfolder. But I dont know how to create the second level of folders nested in some of the first level.
Example: MAIN FOLDER (SELECTED) contain the folders A,B and C the folder A should contain the folder A1 the folder C should contain the folder C1
import pathlib
from tkinter import Tk
from tkinter.filedialog import askdirectory
folder = ["A", "B", "C"]
root = Tk()
root.withdraw()
root.update()
c_path = askdirectory(title='Select Main Folder')
path = c_path + "/"
root.destroy()
for i in folder:
pathlib.Path(path + i).mkdir(parents=True, exist_ok=True)
print("done")
Upvotes: 0
Views: 669
Reputation: 21
thanks to all! I just take the inspiration to finalize the excercise. I guess is not so nice but still work.
import pathlib
import os
from tkinter import Tk
from tkinter.filedialog import askdirectory
folder = ["A", "B", "C", "D", "E", "F"]
subfolder_A = ["/a1"]
subfolder_B = ["/b1", "/b2", "/b3"]
subfolder_F = ["/f1", "/f2"]
root = Tk()
root.update()
c_path = askdirectory(title='Select Main Folder') # shows dialog box and return the path
path = c_path + "/"
root.destroy()
for i in folder:
pathlib.Path(path + i).mkdir(parents=True, exist_ok=True)
for f in subfolder_A:
pathlib.Path(path + folder[0] + f).mkdir(parents=True, exist_ok=True)
for g in subfolder_B:
pathlib.Path(path + folder[3] + g).mkdir(parents=True, exist_ok=True)
for h in subfolder_F:
pathlib.Path(path + folder[5] + h).mkdir(parents=True, exist_ok=True)
os.startfile(path)
print("folder tree created")
Upvotes: 1
Reputation: 18106
You could define a second list (subfolders
) providing your sub directory names:
import pathlib
from tkinter import Tk
from tkinter.filedialog import askdirectory
folder = ["A", "B", "C"]
subfolders = ["1", "2", "3"]
root = Tk()
root.withdraw()
root.update()
c_path = askdirectory(title='Select Main Folder')
path = c_path + "/"
root.destroy()
for f in folder:
for s in subfolders:
subDir = f+s
pth = pathlib.Path(path) / f / subDir
pth.mkdir(parents=True, exist_ok=True)
print(pth, pth.exists())
print("done")
Out:
/private/tmp/nestedPath/A/A1 True
/private/tmp/nestedPath/A/A2 True
/private/tmp/nestedPath/A/A3 True
/private/tmp/nestedPath/B/B1 True
/private/tmp/nestedPath/B/B2 True
/private/tmp/nestedPath/B/B3 True
/private/tmp/nestedPath/C/C1 True
/private/tmp/nestedPath/C/C2 True
/private/tmp/nestedPath/C/C3 True
done
Upvotes: 1