I am trying to get a dictionary from a list of file paths. I have found other methods but they do not go deep into it. I have used the code:
# fs is a list of files
directories = {'': set()}
for f in fs:
splitted = f.split("\\")
directories[''].add(splitted[0])
for i in range(len(splitted)):
if i == len(splitted)-1:
break
d = ''
for j in splitted[0:i 1]:
d = j os.path.sep
d = d[0:-1]
if not d in directories:
directories[d] = set()
directories[d].add(splitted[i 1])
fs is:
['C:\\aydin-os\\filesystem\\', 'C:\\aydin-os\\filesystem\\apps', 'C:\\aydin-os\\filesystem\\apps\\aydin-browse', 'C:\\aydin-os\\filesystem\\apps\\aydin-browse\\main.app', 'C:\\aydin-os\\filesystem\\apps\\calculator', 'C:\\aydin-os\\filesystem\\apps\\calculator\\main.app', 'C:\\aydin-os\\filesystem\\system', 'C:\\aydin-os\\filesystem\\system\\apps', 'C:\\aydin-os\\filesystem\\system\\apps\\apps.stats',
'C:\\aydin-os\\filesystem\\system\\data', 'C:\\aydin-os\\filesystem\\system\\data\\data.stats', 'C:\\aydin-os\\filesystem\\users', 'C:\\aydin-os\\filesystem\\users\\aydin', 'C:\\aydin-os\\filesystem\\users\\aydin\\data', 'C:\\aydin-os\\filesystem\\users\\aydin\\data\\password.stats']
directories is:
{'': {'C:'}, 'C:': {'aydin-os'}, 'C:\\aydin-os': {'filesystem'}, 'C:\\aydin-os\\filesystem': {'', 'apps', 'users', 'system'}, 'C:\\aydin-os\\filesystem\\apps': {'aydin-browse', 'calculator'}, 'C:\\aydin-os\\filesystem\\apps\\aydin-browse': {'main.app'}, 'C:\\aydin-os\\filesystem\\apps\\calculator': {'main.app'}, 'C:\\aydin-os\\filesystem\\system': {'data', 'apps'}, 'C:\\aydin-os\\filesystem\\system\\apps': {'apps.stats'}, 'C:\\aydin-os\\filesystem\\system\\data': {'data.stats'}, 'C:\\aydin-os\\filesystem\\users': {'aydin'}, 'C:\\aydin-os\\filesystem\\users\\aydin': {'data'}, 'C:\\aydin-os\\filesystem\\users\\aydin\\data': {'password.stats'}}
CodePudding user response:
I found out using defaultdict I could nest the file paths. Code for anyone interested:
# fs is the list of the files
for idx in range(len(fs)):
fs[idx] = fs[idx].replace('\\','/').replace('C:/aydin-os/','')
for f in fs:
f2 = f.split('/')
estring = 'files'
for f3 in f2:
if f3 == '':
continue
estring = '["' f3 '"]'
estring = ' = {}'
exec(estring)