This may be confusing.
rootdir= C:\User\Desktop\File
file = 'file.txt'
mainLocNum = str(list(rootdir)).count(r'\\')
mainFolder=os.listdir(rootdir)
with open(file,'w') as f:
for dir, subdirs, files in os.walk(rootdir):
currentDirLevel=str(list(dir)).count(r'\\')
for allFolders in subdirs:
if (currentDirLevel - mainLocNum) == 0:
parentFolders=allFolders
f.write(str(parentFolders))
PLACEHOLDER
elif (currentDirLevel - mainLocNum) == 1:
subFolders=allFolders
f.write(str(allFolders) <----- write this in PLACEHOLDER
I want to write the second write
statement into the PLACEHOLDER
line only if the elif
condition is met. If I don't write the second write
statement in the PLACEHOLDER
position, the second write
statement in the second conditional is written at the very bottom of the text file; however I want to write the second conditional's write
statement (only if it is met) in the PLACEHOLDER
position, which is in between each of the first write
iterations.
I've been trying different nesting methods, but I am lacking in fundamental loop construction logic.
Any help is appreciated, thanks!
EDIT:
I am looping through a main directory, and I am writing all of the parent folders into the text file. I want to write in between each parent folder its subfolders: i.e if the parent folder contains more folders, to write those folders in between each parent folder; and if the parent folder does not contain any more folders, to skip to the next parent folder etc. I am using the if (currentDirLevel - mainLocNum)==(number) to know how many directories it is stepping into and to perform a different write function for each step.
I am trying to write the names of the folders in certain formats depending on whether they are level 1 sub-directories, level 2 sub-directories etc...
What I want:
ParentFolder1
SubFolder1
Subfolder2
SubSubFolder1
SubFolder3
ParentFolder2
SubFolder1
ParentFolder3
ParentFolder4
SubFolder1
SubSubFolder1
SubSubSubFolder1
SubSubFolder2
SubFolder2
ParentFolder5
SubFolder1
What I am getting
ParentFolder1
ParentFolder2
ParentFolder3
ParentFolder4
ParentFolder5
SubFolder1
SubFolder2
SubFolder3
SubFolder1
SubFolder1
SubFolder2
SubFolder1
SubSubFolder1
SubSubFolder1
SubSubFolder2
SubSubSubFolder1
Please don't focus on the os.walk or iterating through the directories. I have a lot of code written already, and I want the main focus to answer my question about running a conditional loop and placing the value within that loop into a write function inside another loop.
I would prefer restructuring this loop logic rather than starting over with the whole os.walk for loop.
Thanks again