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

发布于 2024-07-06 09:43:35 字数 109 浏览 15 评论 0原文

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

在 Python 中是否有类似的方法可以做到这一点?

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

Is there an analogous way to do this in Python?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

对岸观火 2024-07-13 09:43:35

就在这里。 Python 的方式甚至更好。

有三种可能性:

1)像File.listFiles():

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

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

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

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

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

Python的os.walk函数非常好。

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

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 记录在此处

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

There are three possibilities:

1) Like File.listFiles():

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

2) pathname pattern expansion with glob:

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) File Traversal with walk:

Really nice is the os.walk function of Python.

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


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 and walk are documented here.
glob is documented here.

妳是的陽光 2024-07-13 09:43:35

作为一个长期的 Pythonista,我不得不说 std 库中的路径/文件操作函数是低于标准的:它们不是面向对象的,它们反映了过时的,让-wrap-OS-system-functions-without-思维哲学。 我衷心推荐“path”模块作为包装器(如果您必须知道,则围绕 os、os.path、glob 和 tempfile):更好且 OOPy: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()

As a long-time Pythonista, I have to say the path/file manipulation functions in the std library are sub-par: they are not object-oriented and they reflect an obsolete, lets-wrap-OS-system-functions-without-thinking philosophy. I'd heartily recommend the 'path' module as a wrapper (around os, os.path, glob and tempfile if you must know): much nicer and OOPy: http://pypi.python.org/pypi/path.py/2.2

This is walk() with the path module:

dir = path(os.environ['HOME'])
for f in dir.walk():
    if f.isfile() and f.endswith('~'):
        f.remove()
断舍离 2024-07-13 09:43:35

尝试在 os 模块中使用“listdir()”(docs):

import os
print os.listdir('.')

Try "listdir()" in the os module (docs):

import os
print os.listdir('.')
意中人 2024-07-13 09:43:35

直接来自 Python 参考库

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

Straight from Python's Refererence Library

>>> import glob
>>> glob.glob('./[0-9].*')
['./1.gif', './2.txt']
>>> glob.glob('*.gif')
['1.gif', 'card.gif']
>>> glob.glob('?.gif')
['1.gif']
×纯※雪 2024-07-13 09:43:35

查看 os.walk() 和示例 这里。 使用 os.walk() 可以轻松处理整个目录树。

上面链接中的示例...

# 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))

Take a look at os.walk() and the examples here. With os.walk() you can easily process a whole directory tree.

An example from the link above...

# 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))
余罪 2024-07-13 09:43:35

如果您还需要子目录,请使用 os.path.walk。

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.

Use os.path.walk if you want subdirectories as well.

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.
感性 2024-07-13 09:43:35

我建议不要使用 os.path.walk,因为它已在 Python 3.0 中被删除。 无论如何,os.walk 更简单,或者至少发现它更简单。

I'd recommend against os.path.walk as it is being removed in Python 3.0. os.walk is simpler, anyway, or at least I find it simpler.

潇烟暮雨 2024-07-13 09:43:35

您还可以查看 Unipath,Python 操作系统的面向对象包装器, os.pathshutil 模块。

示例:

>>> 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'),
...

通过 Cheese shop 安装:

$ pip install unipath

You can also check out Unipath, an object-oriented wrapper of Python's os, os.path and shutil modules.

Example:

>>> 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'),
...

Installation through Cheese shop:

$ pip install unipath
童话 2024-07-13 09:43:35

由于我已经用Python编程很长时间了,我多次使用os模块并制作了自己的函数来打印目录中的所有文件。

该函数的代码:

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)

Seeing as i have programmed in python for a long time, i have many times used the os module and made my own function to print all files in a directory.

The code for the function:

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文