python achieve matching of multi-level directory content (glob module)

glob module implements the directory content matching , combined with the wildcard asterisk (*) , ** a question mark (?) and brackets ([]) ** use. The asterisk matches zero or more symbols, a question mark (?) Matches a single character in brackets ([]) character matches a specified range.

glob.glob, and () function takes as input a wildcard mode, and returns a list of matching file names and path names, similar os.listdir ().

# *
import glob
for name in glob.glob(r'dir/*'):
    print(name)

dir/file.txt
dir/file1.txt
dir/file2.txt
dir/file3.txt
dir/subdir
# ? 
import glob
for name in glob.glob(r'dir/file?.txt'):
    print(name)

dir/file1.txt
dir/file2.txt
dir/filea.txt
# [ ]
import glob
for name in glob.glob(r'dir/*[0-9].*'):
    print(name)

dir/file1.txt
dir/file2.txt

glob.iglob () function to get a file path name can traverse the object, which gets used individually matched. The difference between glob.glob () is: glob.glob () can get all the matching path at the same time, while glob.iglob () can only get a matching path. This is somewhat similar to the DataSet and DataReader .NET database used in the operation.

import glob
# 父目录中的.py文件
f = glob.iglob(r'../*.py')
print(f)      # generator object iglob as 0x00B9FF80
for py in f:
    print(py)
Published 20 original articles · won praise 30 · views 30000 +

Guess you like

Origin blog.csdn.net/ever_siyan/article/details/104560408