The Os.walk method is used primarily to traverse subdirectories and sub-files within a directory.
Can get a ternary tupple (Dirpath, Dirnames, filenames),
The first is the starting path, the second is the folder under the starting path, and the third is the file under the starting path.
Dirpath is a string that represents the path to the directory,
Dirnames is a list that contains the names of all subdirectories under Dirpath.
Filenames is a list that contains the name of a non-directory file.
These names do not contain path information, and you need to use Os.path.join (Dirpath, name) if you need to get the full path.
Auto-complete recursive enumeration with a for loop
For example:
The F:\AAA directory is such a file directory structure
F:\aaa
|--------1.txt
|--------2.txt
|--------3.txt
|--------4
|-------5.txt
|-------6.txt
|-------7.txt
Print the actual values of each parameter separately
#!/usr/bin/env python#2.py#Use UTF-8#Python 3.3.0 #use of Os.walk ()ImportOS#Enumerate all files under the Dirpath directory defMain ():#beginFiledir ="F:"+ Os.sep +"AAA" #Locate the F:\AAA directory forRoot, dirs, filesinchOs.walk (filedir):#begin Print(Root)Print(dirs)Print(Files)#EndOs.system ("Pause") #End if __name__=='__main__': #beginMain ()#End #Output#F:\aaa#[' 4 ']#[' 1.txt ', ' 2.txt ', ' 3.txt ']#F:\aaa\4# [] #[' 5.txt ', ' 6.txt ', ' 7.txt ']
You can also do this by using tuple A to complete the recursion of the directory with a For loop.
#!/usr/bin/env python#3.py#Use UTF-8#Python 3.3.0 #use of Os.walk ()ImportOS#Enumerate all files under the Dirpath directory defMain ():#beginFiledir ="F:"+ Os.sep +"AAA" #Locate the F:\AAA directory forAinchOs.walk (filedir):#begin Print(a[0])Print(a[1]) Print(a[2]) #EndOs.system ("Pause") #End if __name__=='__main__': #beginMain ()#End #Output#F:\aaa#[' 4 ']#[' 1.txt ', ' 2.txt ', ' 3.txt ']#F:\aaa\4# [] #[' 5.txt ', ' 6.txt ', ' 7.txt ']
You can also do this, first print the catalog, and then print each file
#!/usr/bin/env python#2.py#Use UTF-8#Python 3.3.0 #use of Os.walk ()ImportOS#Enumerate all files under the Dirpath directory defMain ():#beginFiledir ="F:"+ Os.sep +"AAA" #Locate the F:\AAA directory forRoot, dirs, filesinchOs.walk (filedir):#begin forDirinchdirs:#begin Print(Os.path.join (Root, dir))#End forFileinchFiles:#begin Print(Os.path.join (root, file))#End #EndOs.system ("Pause") #End if __name__=='__main__': #beginMain ()#End #Output#F:\aaa\4#F:\aaa\1.txt#F:\aaa\2.txt#F:\aaa\3.txt#F:\aaa\4\5.txt#F:\aaa\4\6.txt#F:\aaa\4\7.txt
Reference
The Os.walk () method for getting started with Python