I am currently learning the basics of Python. At the moment, I am trying to write a script which creates folders (1st hierarchy) from a text file list, each with the the same subfolder structure which goes down to 3 hierarchies.
I've managed to do the first part: Create the 1st hierarchy folders from a text file.
from sys import argv
import os;
home_dir = '/home/tobi/Python'
mylist = open('test.txt','r')
for folder in mylist:
folder = folder.strip()
newFolder = home_dir+'/'+folder
print "Folder name " +newFolder
if not os.path.exists(newFolder):
os.makedirs(newFolder)
os.chdir(newFolder)
mylist.close()
Now I am struggling to create a loop to insert my given subfolder structure in each of the created folder.
How can I do this?
You really should take a break to clear your mind and then rewrite your question, e.g. your question is
Create Folder Hierachy from Text files
but then you write
I've managed to do the first part: Create the 1st hierarchy folders from a text file.
You also contradict yourself about the structure of the subdirectories ... but here's a guess for the flat hierarchy to get you started on your "loop problem". Note that I'm using Python 3, so you might have to adapt a thing or two. Also, I'm not actually creating directories (so this might fail for you and you might have to join paths):
import os
home_dir = "."#'/home/tobi/Python'
# don't have your subdirectory structure, making something up ...
subdirs = [ "{0:02}_Subfolder{0}".format(n) for n in range(1,8+1)]
#with open('test.txt','r') as mylist: # don't have your file, making something up ...
mylist = ["one", "two", "three"]
# indent for with
for folder in mylist:
folder = folder.strip()
newFolder = home_dir + '/' + folder
print("Folder name " + newFolder)
if not os.path.exists(newFolder):
#os.makedirs(newFolder)
print("mkdir:", newFolder) # just pretending
#os.chdir(newFolder)
print("cwd:", newFolder) # just pretending
# just another loop like the one you already came up with (did you really?)
for subdir in subdirs:
if not os.path.exists(subdir):
#os.makedirs(subdir)
print("mkdir:", subdir) # just pretending
# done
gives
Folder name ./one
mkdir: ./one
cwd: ./one
mkdir: 01_Subfolder1
mkdir: 02_Subfolder2
mkdir: 03_Subfolder3
mkdir: 04_Subfolder4
mkdir: 05_Subfolder5
mkdir: 06_Subfolder6
mkdir: 07_Subfolder7
mkdir: 08_Subfolder8
Folder name ./two
mkdir: ./two
cwd: ./two
mkdir: 01_Subfolder1
mkdir: 02_Subfolder2
mkdir: 03_Subfolder3
mkdir: 04_Subfolder4
mkdir: 05_Subfolder5
mkdir: 06_Subfolder6
mkdir: 07_Subfolder7
mkdir: 08_Subfolder8
Folder name ./three
mkdir: ./three
cwd: ./three
mkdir: 01_Subfolder1
mkdir: 02_Subfolder2
mkdir: 03_Subfolder3
mkdir: 04_Subfolder4
mkdir: 05_Subfolder5
mkdir: 06_Subfolder6
mkdir: 07_Subfolder7
mkdir: 08_Subfolder8