Python's Os.walk ()

Source: Internet
Author: User

Original Address https://www.cnblogs.com/JetpropelledSnake/p/8982495.html http://www.runoob.com/python/os-walk.html

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    # os.walk () using  import OS    # Enumerate all files under the Dirpath directory    def Main ():  #begin      filedir = "F:" + os.sep + "AAA"     # Find F:\aaa directory for        Root, dirs, F Iles in Os.walk (filedir):      #begin          Print (root)          print (dirs)          print (files)      #end      Os.system ("pause")  #end    if __name__ = = ' __main__ ':  #begin      Main ()  #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    # os.walk () using  import OS    # Enumerate all files under the Dirpath directory    def Main ():  #begin      filedir = "F:" + os.sep + "AAA"     # Find F:\AAA directory for        A in Os.walk ( Filedir):      #begin          print (a[0])          print (a[1])          print (a[2])      #end      os.system ("pause")  #end    If __name__ = = ' __main__ ':  #begin      Main ()  #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    # os.walk () using  import OS    # Enumerate all files under the Dirpath directory    def Main ():  #begin      filedir = "F:" + os.sep + "AAA"     # Find F:\aaa directory for        Root, dirs, F Iles in Os.walk (filedir):      #begin for          dir in dirs:          #begin              Print (Os.path.join (root, dir))          # End for          file in files:          #begin              Print (os.path.join (root, file))          #end      #end      os.system (" Pause ")  #end    if __name__ = = ' __main__ ':  #begin      Main ()  #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  

Python Os.walk () method

The Os.walk () method is used to go through the directory tree to output the file name in the directory, up or down.

The Os.walk () method is an easy-to-use file and directory Walker that helps us to efficiently handle files and directories.

Valid in Unix,windows.

Grammar

The syntax format for the Walk () method is as follows:

Os.  Walk(top[, topdown=True[, onerror=None[, followlinks= False]])                
Parameters
    • Top --is the address of the directory you want to traverse, and the return is a ternary (root,dirs,files) group.

      • Root refers to the address of the folder itself that is currently being traversed
      • dirs is a list that contains the names of all the directories in the folder (excluding subdirectories)
      • files are also lists, which are all the documents in the folder (excluding subdirectories)
    • Topdown --optional, True to traverse the top directory first, or the top subdirectory (default is on). If the Topdown parameter is True,walk, the top folder is traversed with each subdirectory in the top folder.

    • onerror --optional, requires a callable object, which is called when the walk requires an exception.

    • followlinks -optional, if true, iterates through the directory's shortcuts (symbolic link under Linux) actually refers to the directory (the default is off).

return value

The method has no return value.

Instance

The following example demonstrates the use of the Walk () method:

 #  !/usr/bin/python  #  -*-coding:utf-8-*-  Import   os  for  root, dirs, files in  os.walk ( " .   ", Topdown=false):  for  name in   files:  print   (Os.path.join (root, name))  for  name in   dirs:  print  (Os.path.join (root, name)) 

Execute the above program output as:

./.Bash_logout./Amrood.Tar.Gz./.emacs./httpd. Conf./www.. Gz./mysql.. Gz./test../. Bashrc./. Bash_history./. Bash_profile./tmp./tmp /test.                 

Python's Os.walk ()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.