python--glob文件列表

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 os.listdir() and fnmatch.fnmatch() functions in concert, and not by actually invoking a subshell. (For tilde and shell variable expansion, useos.path.expanduser() and os.path.expandvars().)

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 iteratorwhich yields the same values as glob() 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. glob() 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']

上代碼:


  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


結果:



  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



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章