I want to automate my folder creation using python, the desired hierarchy as picture below,
I created list of the first hierarchy
A.1 = [
'A.1', 'A.2'
]
A.2 = [
'A2.1'
]
This is the main code that i run to automate the folder creation, but i managed to automate it until 2nd hierarchy (A.1.1, A.1.2).
import os
main_dir = [A.1, A.2] # Loading the list of sub-directories
root_dir = 'A'
main_dir_names = ['A.1', 'A.2'] # Name of the sub-directories
def main():
# Create directory
for i in range(0, len(main_dir)):
for j in range(0,len(main_dir[i])):
dirName = str(root_dir) + '/' + str(main_dir_names[i]) +'/' + str(main_dir[i][j])
try:
# Create target Directory
os.makedirs(dirName)
print("Directory " , dirName , " Created ")
except FileExistsError:
print("Directory " , dirName , " already exists")
# Create target Directory if don't exist
if not os.path.exists(dirName):
os.makedirs(dirName)
print("Directory " , dirName , " Created ")
else:
print("Directory " , dirName , " already exists")
if __name__ == '__main__':
main()
Do you guys have any idea how can i automate my code so i can automate folder creation until 3rd hierarchy (A.1.2.1)?
if you provide a 'configuration' for your dir structure like
dir_dict={
'name':'A',
'sub': [{
'name': 'A.1',
'sub':[{
'name': 'A.1.1',
'sub':[]
},{
'name': 'A.1.2',
'sub':[{
'name': 'A.1.2.1',
'sub': []
}]
}]
},{
'name': 'A.2',
'sub':[]
}]
}
then you can iterate through the configuration and create your directories. It's not what you would call 'fully automated' but may be useful in your case.
def create_dir(curr_dir, sub_conf):
curr_dir = curr_dir+'/'+sub_conf['name']
# create dir
print(curr_dir)
for sub in sub_conf['sub']:
create_dir(curr_dir, sub)
create_dir('path_from_root', dir_dict)
If the hierarchy is fixed, you can use os.makedirs()
as follows:
import os
path_1 = os.path.join(os.getcwd(),'A','A1','A11')
path_2 = os.path.join(os.getcwd(),'A','A1','A12','A121')
path_3 = os.path.join(os.getcwd(),'A','A2','A21')
os.makedirs(path_1)
os.makedirs(path_2)
os.makedirs(path_3)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.