代码之家  ›  专栏  ›  技术社区  ›  jjnguy Julien Chastang

在Python中寻找类似Java的文件遍历函数

  •  10
  • jjnguy Julien Chastang  · 技术社区  · 17 年前

    在Java中,您可以 File.listFiles() 并接收目录中的所有文件。然后,您可以轻松地在目录树中递归。

    9 回复  |  直到 17 年前
        1
  •  25
  •   dmeister    17 年前

    是的,有。Python方式甚至更好。

    有三种可能性:

    Python具有函数os.listdir(path)。它的工作原理与Java方法类似。

    2) 使用glob进行路径名模式扩展:

    模块glob包含使用类Unix shell模式列出文件系统上的文件的函数,例如。

    files = glob.glob('/usr/joe/*.gif')
    

    3) 使用walk进行文件遍历:

    Python的os.walk函数非常好。

    import os
    from os.path import join
    for root, dirs, files in os.walk('/usr'):
       print "Current directory", root
       print "Sub directories", dirs
       print "Files", files
    
    您甚至可以动态地从“dirs”中删除目录,以避免走到dirs:dirs.remove(“joe”)中的dir:if“joe”,从而避免走到名为“joe”的目录中。

    listdir和walk都有文档记录 here glob是有文档记录的 here .

        2
  •  5
  •   Max Maximus    17 年前

    http://pypi.python.org/pypi/path.py/2.2

    这是带有路径模块的walk():

    dir = path(os.environ['HOME'])
    for f in dir.walk():
        if f.isfile() and f.endswith('~'):
            f.remove()
    
        3
  •  3
  •   Big Dave Diode    17 年前

    尝试操作系统模块中的“listdir()( docs

    import os
    print os.listdir('.')
    
        4
  •  2
  •   florin    17 年前

    直接来自Python的参考库

    >>> import glob
    >>> glob.glob('./[0-9].*')
    ['./1.gif', './2.txt']
    >>> glob.glob('*.gif')
    ['1.gif', 'card.gif']
    >>> glob.glob('?.gif')
    ['1.gif']
    
        5
  •  2
  •   Joe Skora    17 年前

    看看 os.walk() here . 具有 步行

    上面链接中的一个示例。。。

    # Delete everything reachable from the directory named in 'top',
    # assuming there are no symbolic links.
    # CAUTION:  This is dangerous!  For example, if top == '/', it
    # could delete all your disk files.
    import os
    for root, dirs, files in os.walk(top, topdown=False):
        for name in files:
            os.remove(os.path.join(root, name))
        for name in dirs:
            os.rmdir(os.path.join(root, name))
    
        6
  •  2
  •   Bruno Gomes    17 年前

    walk(top, func, arg)
    
            Directory tree walk with callback function.
    
            For each directory in the directory tree rooted at top (including top
            itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
            dirname is the name of the directory, and fnames a list of the names of
            the files and subdirectories in dirname (excluding '.' and '..').  func
            may modify the fnames list in-place (e.g. via del or slice assignment),
            and walk will only recurse into the subdirectories whose names remain in
            fnames; this can be used to implement a filter, or to impose a specific
            order of visiting.  No semantics are defined for, or required of, arg,
            beyond that arg is always passed to func.  It can be used, e.g., to pass
            a filename pattern, or a mutable object designed to accumulate
            statistics.  Passing None for arg is common.
    
        7
  •  2
  •   giltay    17 年前

    我建议不要 os.path.walk os.walk 不管怎么说,它更简单,或者至少更简单 我觉得更简单。

        8
  •  1
  •   metakermit    12 年前

    你也可以退房 Unipath ,Python的面向对象包装器 os os.path shutil 模块。

    >>> from unipath import Path
    >>> p = Path('/Users/kermit')
    >>> p.listdir()
    Path(u'/Users/kermit/Applications'),
    Path(u'/Users/kermit/Desktop'),
    Path(u'/Users/kermit/Documents'),
    Path(u'/Users/kermit/Downloads'),
    ...
    

    通过奶酪店安装:

    $ pip install unipath
    
        9
  •  0
  •   Hazim Sager    10 年前

    该函数的代码为:

    import os
    
    def PrintFiles(direc):
        files = os.listdir(direc)
        for x in range(len(files)):
            print("File no. "+str(x+1)+": "+files[x])
    
    PrintFiles(direc)