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)
我只能打印子目录。如何将子目录的名称作为列表?
答案 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)