Reputation: 135
I want to write a functions that returns a string with the full path of a file (or none if it is not in the directory tree).
Ex.
pc = ["home",
["Documents",
[ "Tools", "alex.txt", "sport.pdf",
"row" ],
[ "Python", "flatten.py", "set.md" ],
],
["Downloads",
[ "Music",
[ "Movies", "Creed.mp4", "Grinch.avi" ],
"Raplh.avi", "22", "Reg.mp4"
],
],
"trec.txt", "doc.html"
]
finder(pc, 'sport.pdf') should returns the string: "home/Documents/Tools/sport.pdf"
I tried:
path =""
def finder(pc, file_name):
global path
for i in range(len(pc)-1):
if isinstance(pc[i], list):
finder(pc[i], file_name)
else:
if pc[i]==file_name:
path="/"+file_name
return(path)
print(finder(pc, 'sport.pdf'))
return:
/sport.pdf
But how can I have the full path: home/Documents/Tools/sport.pdf
Thanks in advance
Upvotes: 1
Views: 131
Reputation: 71451
You can use recursion with a generator:
pc = ['home', ['Documents', ['Tools', 'alex.txt', 'sport.pdf', 'row'], ['Python', 'flatten.py', 'set.md']], ['Downloads', ['Music', ['Movies', 'Creed.mp4', 'Grinch.avi'], 'Raplh.avi', '22', 'Reg.mp4']], 'trec.txt', 'doc.html']
def finder(_tree, _filename, _current=''):
if _filename in _tree:
yield f'{_current}/{_filename}'
else:
_dir, *_files = _tree
for _row in _files:
yield from finder(_row, _filename, f'{_current}/{_dir}' if _current else _dir)
print(list(finder(pc, 'sport.pdf'))[0])
Output:
'home/Documents/sport.pdf'
Upvotes: 1