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

标签 python string list recursion nested

我想编写一个函数,它返回一个带有文件完整路径的字符串(如果不在目录树中,则返回无)。

例如。

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/

相关文章:

c# - 在 C# 中引用另一个字符串

c++ - std::list 反向迭代和删除导致崩溃

python - 获取调用该函数的文件的绝对路径

python - PyTorch:为什么要创建同一类型层的多个实例?

python - 如何使用unittest在Python中编写测试

java - 从字符串数组中删除空值的最佳方法

python - 如何在 folium 中创建相对于 map 的固定大小的标记?

Python:将字符串中的字符替换为另一个字符串中的等效字符

Python 扩展了一个空列表错误?

python - 用另一个包含数组的列表索引一个列表