我想编写一个函数,该函数返回具有文件完整路径的字符串(如果不在目录树中,则返回完整字符串)。
例如。
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')应该返回字符串: “主页/文档/工具/sport.pdf”
我尝试过:
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'))
返回:
/sport.pdf
但是我如何获得完整路径: 主页/Documents/Tools/sport.pdf
预先感谢
答案 0 :(得分:1)
您可以将递归与生成器一起使用:
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])
输出:
'home/Documents/sport.pdf'