Python traverse all files and directories in a folder
Walking through all subfolders and subfiles in a folder is very simple using the os.walk() method.
The syntax is roughly as follows:
os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])
- top - For each folder in the root directory (including itself), generate a 3-tuple (dirpath, dirnames,
filenames) [folder path, folder name, filename].
- topdown – optional, true or not specified, a directory's 3-tuple will be generated before any of its subfolders' 3-tuple
(directory top-down). If topdown is False, the 3-tuple of a directory will be generated after the 3-tuple of any of its subfolders (directories bottom-up).
- onerror – optional, is a function; it is called with one parameter, an instance of OSError. After reporting this error, continue the walk, or throw an exception to terminate the walk.
- followlinks – set to true to access directories via soft links.
The example is as follows:
Display all files in a directory
#conding=utf8 import os g = os.walk(r"e:\test") for path,dir_list,file_list in g: for file_name in file_list: print(os.path.join(path, file_name) )
show all subdirectories
#conding=utf8 import os g = os.walk("e:\test") for path,dir_list,file_list in g: for dir_name in dir_list: print(os.path.join(path, dir_name) )