It has the following directory (red) and file (black) tree structure, where my current python code me
is located.
Task: Traverse all the directories and files in the file directory and print the names.
import os
for parent,dirnames,filenames in os.walk("./file"):
print(parent,dirnames,filenames)
The walk()
function is the meaning of traversal, which means the relative path "./file"
based on the current code ( me
) (absolute path can also be used).
The results are as follows:
Analysis: The walk()
function is fixed to have 3 items in each line, but the number of lines is not fixed, because if there are many directories, there will be more lines. In addition, the order of lines is from parent directory to subdirectory by default. Corresponding to the above print result, there are:
- The first item
parent
represents the root directory currently traversed, and then search down to get the directoriesdir
and filesfile
, which are all represented by lists. - According to the rules of level traversal, the current root directory is changed to
file1
and continue to explore. - 。。。。。。
Summary: Level traversal.