In Python, I want to go list all the directories in a root directory, and print out the directory number together with the directory. 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
, i.e. the number of the directory in the root directory? 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()
...
The Python os. listdir() method returns a list of every file and folder in a directory. os. walk() function returns a list of every file in an entire file tree.
OS. walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). root : Prints out directories only from what you specified.
os. walk() returns a list of three items. It contains the name of the root directory, a list of the names of the subdirectories, and a list of the filenames in the current directory.
You can still use 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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With