gpt4 book ai didi

python - 文件名和路径的问题

转载 作者:行者123 更新时间:2023-11-30 23:49:41 25 4
gpt4 key购买 nike

以下示例“遍历”一个目录,打印所有文件的名称,并在所有目录上递归调用自身。

import os
def walk(dir):
for name in os.listdir(dir):
path = os.path.join(dir,name)
if os.path.isfile(path):
print path
else:
walk1(path)

os.path.join` takes a directory and a file name and joins them into a complete path.

我的练习:修改walk,以便它不打印文件名称,而是返回名称列表。

有人可以解释一下这个函数每行做了什么吗?我有一个好主意,但是当它到达以下行时:else: walk(path),这让我感到困惑,因为没有解释它在做什么。对于本练习,我认为将其更改为列表的唯一方法是:

def walk1(dir):
res = []
for name in os.listdir(dir):
path = os.path.join(dir,name)
if os.path.isfile(path):
res.append(path)
else:
walk1(path)
return res

我的输出从如此多的输出行减少到只有很少的输出行。我这样做正确吗?

最佳答案

这是一个带注释的版本,其中对递归进行了一些小修复。

def walk1(dir):
res = []
# for all entries in the folder,
for name in os.listdir(dir):
# compute the path relative to `dir`
path = os.path.join(dir,name)
# include entries recursively.
if os.path.isfile(path):
# the path points to a file, save it.
res.append(path)
else:
# the path points to a directory, so we need
# to fetch the list of entries in there too.
res.extend(walk1(path))
# produce all entries at once.
return res

关于python - 文件名和路径的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7563205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com