How to Use the glob module in Python to find the file path
This article mainly introduces how to use the glob module in Python to find the file path. It is very simple to use the iglob method in the module. For more information, see
The glob module is one of the simplest modules with very little content. You can use it to find the path name of a file that complies with specific rules. It is similar to searching files in windows. Only three matching characters are used for searching a file: "*", "?", "[]"." * "Matches 0 or multiple characters ;"?" Match a single character. "[]" matches characters in the specified range, for example, [0-9] matches numbers.
Glob. glob
Returns the list of all matched file paths. It has only one pathname parameter and defines the file path matching rule. Here it can be an absolute path or a relative path. The following is an example of using glob. glob:
?
1 2 3 4 5 6 7 8 |
Import glob # Retrieving all images in a specified directory Print glob. glob (r "E:/Picture/*. jpg ") # Retrieve all. py files in the parent directory Print glob. glob (R' ../*. py ') # Relative Path |
Glob. iglob
Obtain a programmable object, which can be used to obtain matching file path names one by one. The difference with glob. glob () Is that glob. glob obtains all matching paths at the same time, while glob. iglob obtains only one matching path at a time. This is a bit similar to DataSet and DataReader used to operate databases in. NET. The following is a simple example:
?
1 2 3 4 5 6 7 8 9 10 |
Import glob #. Py file in the parent directory F = glob. iglob (R' ../*. py ') Print f # <Generator object iglob at 0x00B9FF80> For py in f: Print py |
It's so easy, isn't it?