Reputation: 15
I have a list that contains folders names with paragraph numbers (extracted from a word file with pydocx)
list = [
"1. Références",
"2. Identification de l’équipement sous test",
"3. Moyens de test",
"4. Configurations matérielle et logicielle",
"4.1. Configuration matérielle de base",
"4.2. Configuration Application",
"file1.txt",
"file2.txt",
"5. Tests fonctionnels",
"5.1. Démarrage",
"5.2. Réglages",
"file1.txt",
"file2.txt",
"file3.txt",
"5.3. Signalisation",
"file1.txt",
"file2.txt",
"file3.txt",
"file4.txt",
"5.3.1. LED Focus",
"file1.txt",
"file2.txt",
"file3.txt",
"file4.txt",
"file5.txt",
"5.3.2. LED Verrou",
"5.3.3. LED Apprentissage",
"5.3.4. LED Fin de course",
"5.3.5. LED Défaut",
"5.3.6. LED Fonctionnement",
"5.3.7. Buzzer",
"5.4. Bornier Commande",
"5.4.1. Sans fonction",
"5.4.1.1. Entrée E1",
"5.4.1.2. Entrée E2",
.
.
.
]
I want to convert these elements to path directories, in order to create a tree folders. for example: I want to have folder directories like this:
and so one ...
I really appreciate your suggestion, cause I've tired every think, but i didnt get what I want. Thank you for your help.
Upvotes: 0
Views: 299
Reputation: 89
I will explain everything here:
There is the code:
import re
paths = []
parentStack = []
def addPath(value, isDirectory):
path = ""
for i in range(len(parentStack)):
path += "/" + parentStack[i][1] # Complete name folder
parentStack[i] = (parentStack[i][0], parentStack[i][1], True)
path += "/" + value
if isDirectory:
path += "/"
paths.append(path)
def returnPaths(list):
for elem in list:
value = elem.split(" ")[0] # Taking the number directory
if re.match("([0-9]+\.)+", value) == None:
addPath(elem, False)
else:
if not parentStack:
parentStack.append((value, elem, False))
else:
added = False
while parentStack:
isSon = True
parent = parentStack[-1][0] # I'm taking the number of the directory here
for i in range(len(parent)):
if (len(value) > i and parent[i] != value[i]):
folder = parentStack.pop()
isSon = False
if not folder[2]:
addPath(folder[1], True)
break
if isSon:
added = True
parentStack.append((value, elem, False))
break
if not added:
parentStack.append((value, elem, False))
return paths
Upvotes: 1