python: glob module

 

Introduction to glob of python standard library

 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

#用子目录查询文件
print ('Named explicitly:')
for name in glob.glob('dir/subdir/*'):
    print ('\t', 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

Reprinted from: https://www.cnblogs.com/luminousjj/p/9359543.html

Guess you like

Origin blog.csdn.net/Answer3664/article/details/103465346