简体   繁体   English

Python:使用递归返回文件的完整路径

[英]Python: returns the full path of a file with recursion

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" finder(pc, 'sport.pdf') 应该返回字符串:“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 /体育.pdf

But how can I have the full path: home/Documents/Tools/sport.pdf但是我怎么能有完整的路径:home/Documents/Tools/sport.pdf

Thanks in advance提前致谢

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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM