glob是python自己带的一个文件操作相关模块,用它可以查找符合自己目的的文件,就类似于Windows下的文件搜索,支持通配符操作,*,?,[]这三个通配符,*代表0个或多个字符,?代表一个字符,[]匹配指定范围内的字符,如[0-9]匹配数字。

它的主要方法就是glob,该方法返回所有匹配的文件路径列表,该方法需要一个参数用来指定匹配的路径字符串(本字符串可以为绝对路径也可以为相对路径),其返回的文件名只包括当前目录里的文件名,不包括子文件夹里的文件

python手机中的介绍:

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched. This is done by using the and functions in concert, and not by actually invoking a subshell. (For tilde and shell variable expansion, use and .)

glob.
glob
(
pathname
) #返回列表
Return a possibly-empty
list of path names that match
pathname, which must be a string containing a path specification.
pathname can be either absolute (like
/usr/src/Python-1.5/Makefile) or relative (like
../../Tools/*/*.gif), and can contain shell-style wildcards. Broken symlinks are included in the results (as in the shell).
glob.
iglob
(
pathname
) #返回迭代器

Return an which yields the same values as without actually storing them all simultaneously.

New in version 2.5.

For example, consider a directory containing only the following files: 1.gif, 2.txt, and card.gif. will produce the following results. Notice how any leading components of the path are preserved.

>>> importglob>>> glob.glob('./[0-9].*')['./1.gif', './2.txt']>>> glob.glob('*.gif')['1.gif', 'card.gif']>>> glob.glob('?.gif')['1.gif']

上代码:

[python]
  1. import glob

  2. fileList = glob.glob(r'c:\*.txt')

  3. print fileList

  4. for file_name in fileList:

  5. print file_name

  6. print'*'*40

  7. fileGen = glob.iglob(r'c:\*.txt')

  8. print fileGen

  9. for filename in fileGen:

  10. print filename


结果:

[python]
  1. ['c:\\1.txt', 'c:\\adf.txt', 'c:\\baidu.txt', 'c:\\resultURL.txt']

  2. c:\1.txt

  3. c:\adf.txt

  4. c:\baidu.txt

  5. c:\resultURL.txt

  6. ****************************************

  7. <generator object iglob at 0x01DC1E90>

  8. c:\1.txt

  9. c:\adf.txt

  10. c:\baidu.txt

  11. c:\resultURL.txt