gpt4 book ai didi

python - 如何以列表形式获取代码的输出?

转载 作者:太空宇宙 更新时间:2023-11-04 05:29:29 26 4
gpt4 key购买 nike

import os

for dirname, dirnames, filenames in os.walk('.'):
# print path to all subdirectories first.
for subdirname in dirnames:
print os.path.join(dirname, subdirname)

# print path to all filenames.
for filename in filenames:
print os.path.join(dirname, filename)

我只能打印子目录。如何以列表形式获取子目录的名称?

最佳答案

声明一个列表来收集 for 循环之外的名称。 append 到循环内的该列表。

import os

subdirs = []

for dirname, dirnames, filenames in os.walk('.'):
# collect path to all subdirectories first.
for subdirname in dirnames:
name = os.path.join(dirname, subdirname)
subdirs.append(name)

# print path to all filenames.
for filename in filenames:
print(os.path.join(dirname, filename))

print(subdirs)

关于python - 如何以列表形式获取代码的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24430259/

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