[英]Python: os.walk() with enumeration
In Python, I want to go list all the directories in a root directory, and print out the directory number together with the directory. 在Python中,我想列出根目录中的所有目录,并将目录号与目录一起打印出来。 I then want to print out the files in that directory. 然后我想打印出该目录中的文件。
The code would be something like: 代码如下:
for subdir, dirs, files in os.walk(root_dir):
print "Directory " + str(dir_num) + " = " subdir
for (file_num, file) in enumrate(files):
print "File " + str(file_num) + " = " file
But how do can I get a value for dir_num
, ie the number of the directory in the root directory? 但是如何获取dir_num
的值,即根目录中的目录号? I know how to do this to print the file number, using enumerate()
, but I'm unsure as to how to apply this to os.walk()
... 我知道如何使用enumerate()
打印文件号,但我不确定如何将其应用于os.walk()
...
You can still use enumerate()
: 你仍然可以使用enumerate()
:
for dirnum, (subdir, dirs, files) in enumerate(os.walk(root_dir)):
You need the parentheses around subdir, dirs, files
because enumerate()
will return only two items: the index and the tuple subdir, dirs, files
. 你需要在subdir, dirs, files
周围的括号subdir, dirs, files
因为enumerate()
只返回两个项目:索引和元组subdir, dirs, files
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.