我想编写一个函数,它返回一个带有文件完整路径的字符串(如果不在目录树中,则返回无)。
例如。
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'))
返回:
/运动.pdf
但是我怎样才能获得完整路径: 主页/文档/工具/sport.pdf
提前致谢
最佳答案
您可以使用带有生成器的递归:
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'
关于Python:使用递归返回文件的完整路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53980322/