如何在 os.listdir 中查找文件和跳过目录 [英] How to find files and skip directories in os.listdir

查看:149
本文介绍了如何在 os.listdir 中查找文件和跳过目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 os.listdir 并且它工作正常,但我也在列表中得到了子目录,这不是我想要的:我只需要文件.

I use os.listdir and it works fine, but I get sub-directories in the list also, which is not what I want: I need only files.

为此我需要使用什么函数?

What function do I need to use for that?

我还查看了 os.walk,它似乎是我想要的,但我不确定它是如何工作的.

I looked also at os.walk and it seems to be what I want, but I'm not sure of how it works.

推荐答案

需要过滤掉目录;os.listdir() 列出给定路径中的所有名称.您可以使用 os.path.isdir() 为此:

You need to filter out directories; os.listdir() lists all names in a given path. You can use os.path.isdir() for this:

basepath = '/path/to/directory'
for fname in os.listdir(basepath):
    path = os.path.join(basepath, fname)
    if os.path.isdir(path):
        # skip directories
        continue

请注意,这只会在跟随符号链接后过滤掉目录.fname 不一定是普通文件,它也可以是文件的符号链接.如果您还需要过滤掉符号链接,则需要使用 不是 os.path.islink() 首先.

Note that this only filters out directories after following symlinks. fname is not necessarily a regular file, it could also be a symlink to a file. If you need to filter out symlinks as well, you'd need to use not os.path.islink() first.

在现代 Python 版本(3.5 或更高版本)上,更好的选择是使用 os.scandir() 函数;这会产生 DirEntry() 实例.在一般情况下,这会更快,因为加载的目录已经缓存了足够的信息来确定条目是否为目录:

On a modern Python version (3.5 or newer), an even better option is to use the os.scandir() function; this produces DirEntry() instances. In the common case, this is faster as the direntry loaded already has cached enough information to determine if an entry is a directory or not:

basepath = '/path/to/directory'
for entry in os.scandir(basepath):
    if entry.isdir():
        # skip directories
        continue
    # use entry.path to get the full path of this entry, or use
    # entry.name for the base filename

如果只需要常规文件(而不是符号链接),您可以使用 entry.is_file(follow_symlinks=False).

You can use entry.is_file(follow_symlinks=False) if only regular files (and not symlinks) are needed.

os.walk() 在幕后做同样的工作;除非你需要向下递归子目录,否则你不需要在这里使用 os.walk().

os.walk() does the same work under the hood; unless you need to recurse down subdirectories, you don't need to use os.walk() here.

这篇关于如何在 os.listdir 中查找文件和跳过目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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