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

2024-04-26 22:57:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个函数,返回一个字符串和一个文件的完整路径(或无,如果它不在目录树)。你知道吗

例如

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"
]

查找器(pc,'体育.pdf“)应返回字符串: “主页/文档/工具/体育.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你知道吗

但我怎样才能得到完整的路径: 主页/文档/工具/体育.pdf你知道吗

提前谢谢


Tags: 工具path字符串name文档路径txtpdf
1条回答
网友
1楼 · 发布于 2024-04-26 22:57:14

可以对生成器使用递归:

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'

相关问题 更多 >