Objective
How do I traverse to find all the sub-files within a folder? and find out all the files for a suffix
Introduction to walk Features
The 1.os.walk () method is used to output the file name in the directory through the directory tree Walk, up or down.
The 2.walk () method syntax is formatted as follows:
Os.walk (Top,topdown=true,onerror=none, Followlinks=false)
Top root directory of each folder (including itself), resulting in 3-tuple (Dirpath, dirnames, filenames) "Folder path, folder name, file name."
Topdown optional, true or unspecified, a 3-tuple of a directory will be generated first (directory top-down) than the 3-tuple of any of its subfolders. If Topdown is False, a 3-tuple of a directory will be generated after the 3-tuple of any of its subfolders (directory bottom-up).
OnError Optional, is a function; It is called when there is a parameter, an OSError instance. After reporting this error, continue to walk, or throw exception to terminate walk.
Followlinks is set to True, the directory is accessed through a soft link.
Above reference Document Http://www.runoob.com/python/os-walk.html
Traversing files
1. The first parameter, Fpath, is to traverse all the file paths of the print
# coding:utf-8import ospath = r"D:\test\python2" # 查找文件的路径for fpath, dirname, fnames in os.walk(path): print(fpath) # 所有的文件夹路径 公众号:yoyoketang
2. The second parameter dirname is to traverse all the folder names that are printed
# coding:utf-8import ospath = r"D:\test\python2" # 查找文件的路径for fpath, dirname, fnames in os.walk(path): print(dirname) # 所有的文件名 公众号:yoyoketang
3. The third parameter, Fnames, is to traverse all the file names
# coding:utf-8import ospath = r"D:\test\python2" # 查找文件的路径for fpath, dirname, fnames in os.walk(path): print(fnames) # 所有的文件名 公众号:yoyoketang
Traverse all the files
1. Traverse the lookup folder for all sub-files (not including folders)
2. Use EndsWith to determine if the lookup is after the. Py End
# Coding:utf-8Import OSdef get_files ' d:\\xx ', Rule= ". Py"): all = [ ] for fpathe,dirs,fs in Os.walk (PATH): # Os.walk is to get all the directories for F in FS: filename = Os.path.join (fpathe,f) if filename.endswith (rule): # determine if it is "xxx" ending all.append (filename) return allif __name__ = = " __main__ ": b = get_files (r" D:\test \python2 ") for i in B: print I
Python Note 4-Traverse folder directory Os.walk ()