The glob file name pattern matches, without traversing the entire directory to determine whether each file matches.
1、 Wildcard
An asterisk (*) matches zero or more characters
import glob
for name in glob.glob('dir/*'):print(name)
dir/file.txt
dir/file1.txt
dir/file2.txt
dir/filea.txt
dir/fileb.txt
dir/subdir
To list files in a subdirectory, you must include the subdirectory name in the pattern:
import glob
# Query files with subdirectories
print('Named explicitly:')for name in glob.glob('dir/subdir/*'):print('\t', name)
# Use wildcards*Instead of subdirectory name
print('Named with wildcard:')for name in glob.glob('dir/*/*'):print('\t', name)
Named explicitly:
dir/subdir/subfile.txt
Named with wildcard:
dir/subdir/subfile.txt
2、 Single character wildcard
Use a question mark (?) to match any single character.
import glob
for name in glob.glob('dir/file?.txt'):print(name)
dir/file1.txt
dir/file2.txt
dir/filea.txt
dir/fileb.txt
3、 Character range
When you need to match a specific character, you can use a range
import glob
for name in glob.glob('dir/*[0-9].*'):print(name)
dir/file1.txt
dir/file2.txt
Knowledge point supplement: Python programming: glob module for file name pattern matching
File preparation
mkdirtmp cd tmp touchfile1.txt touch file2.txt touchfile3.log ls file1.txt file2.txt file3.log
test
import glob
# Use zero or more character wildcards*
glob.glob("tmp/*.txt")
Out[1]:['file1.txt','file2.txt']
# Use single-character wildcards?
glob.glob("tmp/file?.txt")
Out[2]:['file1.txt','file2.txt']
# Use range matching
glob.glob("tmp/file[0-9].txt")
Out[3]:['file1.txt','file2.txt']
to sum up
So far, this article on the analysis of glob in the python standard library is introduced. For more relevant python standard library glob content, please search for ZaLou.Cn's previous articles or continue to browse related articles below. Hope you will support ZaLou more in the future .Cn!
Recommended Posts