os.walk(path) traverse all directories and files under path

It has the following directory (red) and file (black) tree structure, where my current python code meis located.
Insert picture description here
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:
Insert picture description here
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:

  1. The first item parentrepresents the root directory currently traversed, and then search down to get the directories dirand files file, which are all represented by lists.
  2. According to the rules of level traversal, the current root directory is changed to file1and continue to explore.
  3. 。。。。。。

Summary: Level traversal.

Guess you like

Origin blog.csdn.net/qq_43391414/article/details/113407495
Recommended