在Python中寻找类似Java的文件遍历函数 [英] Looking for File Traversal Functions in Python that are Like Java's

查看:146
本文介绍了在Python中寻找类似Java的文件遍历函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In Java you can do File.listFiles() and receive all of the files in a directory. You can then easily recurse through directory trees.

在Python中有类似的方法吗?

Is there an analogous way to do this in Python?

推荐答案

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

Yes, there is. The Python way is even better.

有三种可能性:

1)与文件类似。 listFiles():

Python具有os.listdir(path)函数。它就像Java方法一样。

Python has the function os.listdir(path). It works like the Java method.

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

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

The module glob contains functions to list files on the file system using Unix shell like pattern, e.g.


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

3)文件遍历行走:

真的nice是Python的os.walk函数。

Really nice is the os.walk function of Python.

walk方法返回一个生成函数,该函数以递归方式列出给定起始路径下的所有目录和文件。

The walk method returns a generation function that recursively list all directories and files below a given starting path.

示例:

An Example:


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中的joe:dirs.remove( joe)避免进入名为joe的目录。

You can even on the fly remove directories from "dirs" to avoid walking to that dir: if "joe" in dirs: dirs.remove("joe") to avoid walking into directories called "joe".

listdir和walk记录在案这里
glob记录在此处

listdir and walk are documented here. glob is documented here.

这篇关于在Python中寻找类似Java的文件遍历函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆