如何在os.listdir中查找文件并跳过目录

52 投票
8 回答
107421 浏览
提问于 2025-04-17 20:59

我用 os.listdir 来列出文件夹里的内容,这个方法很好用,但它也把子文件夹列出来了,这不是我想要的:我只需要文件。

那我该用哪个函数呢?

我也看了 os.walk,感觉这个可能符合我的需求,但我不太明白它是怎么工作的。

8 个回答

2

使用os.walk()的解决方案是:

for r, d, f in os.walk('path/to/dir'):
    for files in f:
       # This will list all files given in a particular directory
7

在编程中,有时候我们会遇到一些问题,可能会让我们感到困惑。比如,有人可能在使用某个工具或语言时,遇到了错误或者不明白的地方。这种情况下,大家通常会去网上查找解决方案,像StackOverflow这样的网站就是一个很好的地方。在这里,程序员们会分享他们的经验和解决办法,帮助其他人解决类似的问题。

如果你在学习编程,遇到问题时,不妨去看看这些讨论,可能会找到对你有帮助的答案。记得多尝试,多问问题,这样才能更快地进步哦!

for fname in os.listdir('.'):
    if os.path.isdir(fname):
       pass  # do your stuff here for directory
    else:
       pass  # do your stuff here for regular file
8
import os
directoryOfChoice = "C:\\" # Replace with a directory of choice!!!
filter(os.path.isfile, os.listdir(directoryOfChoice))

附注:os.getcwd() 会返回当前的文件夹路径。

28

这里有一个很简洁的写法,使用了列表推导式:

[f for f in os.listdir(your_directory) if os.path.isfile(os.path.join(your_directory, f))]

这个代码会返回一个包含指定目录 your_directory 中所有文件名的 list

75

你需要过滤掉文件夹;os.listdir() 会列出指定路径下的所有 名称。你可以用 os.path.isdir() 来做到这一点:

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 不一定是一个 普通文件,它也可能是指向某个文件的符号链接。如果你还想过滤掉符号链接,你需要先用 not os.path.islink()

在现代的 Python 版本(3.5 或更新)中,更好的选择是使用 os.scandir() 函数;这个函数会生成 DirEntry() 实例。在常见情况下,这个方法更快,因为 direntry 已经缓存了足够的信息,可以判断一个条目是否是文件夹:

basepath = '/path/to/directory'
for entry in os.scandir(basepath):
    if entry.is_dir():
        # 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)

os.walk() 在后台做了同样的工作;除非你需要递归进入子文件夹,否则这里不需要使用 os.walk()

撰写回答