Python - os.walk () using detailed

os.walk () method brief

  • Mainly used to traverse the subdirectories and files in a sub-directory
  • Is an easy to use file, directory traversal, you can help us efficient processing files, directories aspects of things.

 

Method parameters introduced

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]]) 

  • Top  : is the address you want to traverse the directory, returns a triple  (dirpath, dirnames, filenames) 
  • the topdown  : Optional, True the first traversal of the top folder, a subdirectory for each and top folder; otherwise traverse the top priority subdirectories (on by default).
  • onerror  : Optional, requires a callable object that needs an exception when the walk, will call
  • followlinks  : Optional If True, Shortcuts in the directory will traverse (under linux is a soft link symbolic link) within the meaning of the actual directory (off by default), if False, the first traversal of the top subdirectories

 

Introduction returned triples

dirpath  : String, path represents a directory,

dirnames  : List, containing the names of all the subdirectories under dirpath.

filenames  : List, containing the names of non-directory files.

 

Simple code implementation

path = os.getcwd()for dirpath, dirnames, filenames in os.walk(path):
    print(dirpath)
    print(dirnames)
    print(filenames)

 

Test Results

F:\pylearn\learn
['test']
['bytes_str.py', 'get_file_md5_test.py', 'List_Tuple_Learning.py', 'Number_Learning.py', 'os_walk.py', 'String_Learning.py', '__init__.py']
F:\pylearn\learn\test
[]
['test.py', '__init__.py']

 

It includes knowledge

When you can see the top when there is a directory path, it will recursive query

The above code is equivalent to the following code, of course, is not recommended to write, because not enough clarity

for data in os.walk(path):
    print(data[0])
    print(data[1])
    print(data[2])

 

Guess you like

Origin www.cnblogs.com/poloyy/p/12349230.html
Recommended