zoukankan      html  css  js  c++  java
  • 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, use os.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 iterator which 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.gif2.txt, and card.gifglob() will produce the following results. Notice how any leading components of the path are preserved.

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

    上代码:

    [python] view plain copy
     
     print?
    1. import glob  
    2. fileList = glob.glob(r'c:*.txt')  
    3. print fileList  
    4. for file_name in fileList:  
    5.     print file_name  
    6.   
    7. print '*'*40  
    8. fileGen = glob.iglob(r'c:*.txt')  
    9. print fileGen  
    10. for filename in fileGen:  
    11.     print filename  


    结果:

    [python] view plain copy
     
     print?
      1. ['c:\1.txt', 'c:\adf.txt', 'c:\baidu.txt', 'c:\resultURL.txt']  
      2. c:1.txt  
      3. c:adf.txt  
      4. c:aidu.txt  
      5. c: esultURL.txt  
      6. ****************************************  
      7. <generator object iglob at 0x01DC1E90>  
      8. c:1.txt  
      9. c:adf.txt  
      10. c:aidu.txt  
      11. c: esultURL.txt  
  • 相关阅读:
    java简单学习笔记20181228
    java简单学习笔记20181226
    java简单学习笔记20181225
    java简单学习笔记20181224
    java简单学习笔记20181221
    java简单学习笔记20181219
    java简单学习笔记20181218
    java简单学习笔记20181217
    java简单学习笔记201812013
    java简单学习笔记20181205
  • 原文地址:https://www.cnblogs.com/liuzhiyun/p/7118755.html
Copyright © 2011-2022 走看看