【发布时间】:2022-01-08 21:09:13
【问题描述】:
我有上面的树。我需要以递归方式搜索树中的目录和文件,并将它们作为字典以以下形式返回-> 键:文件的目录/名称和值:文件的第一行
eg: key:1/2/5/test5 value:first line of test 5
到目前为止,我创建了下一个代码:
def search(root):
items = os.listdir(root)
for element in items:
if os.path.isfile(element):
with open (element) as file:
one_line=file.readline()
print(one_line)
elif os.path.isdir(element):
search(os.path.join(root,element))
问题是我的代码只搜索目录。请让我明白我错在哪里以及如何解决它。非常感谢任何帮助,谢谢!
【问题讨论】:
-
my code only searches the directories是什么意思?为什么不在打印one_line之前使用字典保存文件信息?
标签: python file recursion directory