To traverse the file name in a directory, it is convenient to use Os.walk. He returns a list of tuples as elements. Each element contains three contents: a path, a subdirectory under that path, and a file under that path.
Os.walk uses the generator technology (refer to other documentation or technical information) yield, which gives the user great flexibility in use. Because the generator technology makes the call of function walk return only one tuple at a time, it saves memory space and improves execution efficiency.
For example, the user only wants to get the current directory level of the file, but do not want to recursively its subdirectory functions. If walk does not use the generator technology, it may be necessary to control whether the subdirectory is recursive by using the pass parameter, or whether the recursive subdirectory is managed separately using two functions. Also, you need to add parameters if you need to control the recursive hierarchy. If you don't want to be so troublesome, you can get all the files in the directory at once (including subdirectories) and then use the files as needed, but the result is that time and space are a huge waste.
The yield technique is used, because the generator generates only one directory-level content at a time, saves space, and gives control to the user, and the user decides whether or not to recursively return subdirectories.
The main function allfiles in this paper also uses the generator technique, which returns a required file at a time rather than returning all the required lists at once, and also has a good performance in terms of flexibility and efficiency.
In addition, Allfiles has added some personalized features:
1, through the Fnmatch to the desired file format matching filtering, want to match the file in the parameter patterns through the semicolon pass the file to match the kind. For example *
, the representative matches all files, *txt
representing the files that match all of the suffix txt.
2 single_level
. True indicates that only one level of directory is processed, and false means that the subdirectory is recursively processed. 3, Yield_folders indicates whether the matching directory is also output.
# root directory, patterns match file format, single_level whether to do directory deep searchImportFnmatch, OS def allfiles(root, Patterns = ' * ', Single_level = False, Yield_folders = False): Patterns = Patterns.split ('; ') forPath, subdirs, filesinchOs.walk (Root):ifYield_folders:#add subdirs to the tail of filesFiles.extend (Subdirs) Files.sort () forNameinchFiles forPatterninchPatternsifFnmatch.fnmatch (name, pattern):yieldOs.path.join (path, name) Break #only deal one level of the Dir ifSingle_level: Break forNameinchAllfiles (' I:\\ptest ', Single_level =True): Print (name)
Working with Python directory (i): Print the file name under the directory