如何将代码输出作为列表?

时间:2014-06-26 12:14:16

标签: python linux

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)

我只能打印子目录。如何将子目录的名称作为列表?

1 个答案:

答案 0 :(得分:0)

声明一个列表以收集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)