python - 如何在 os.listdir 中查找文件和跳过目录

标签 python file-manager

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

为此我需要使用什么功能?

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

最佳答案

你需要过滤掉目录; 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

请注意,这仅在遵循符号链接(symbolic link)后过滤掉目录fname 不一定是常规文件,它也可以是文件的符号链接(symbolic link)。如果您还需要过滤掉符号链接(symbolic link),则需要使用 not os.path.islink()首先。

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

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

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

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

关于python - 如何在 os.listdir 中查找文件和跳过目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22207936/

相关文章:

python - SimpleXMLRPCServer 是单线程的吗?

python - python 有选择地抑制输出

python : How to import list of files in directory from HDFS

python - 通过Python从网站解析数据中以utf-8进行解码

javascript - Simogeo FileManager 不显示图像

asp.net - 用于 ASP.NET 的 KCFinder

macos - 在终端(OSX)中创建大量指定大小的文件?

swift - 删除和图像并再次重新写入会产生错误

每次启动/重新运行应用程序时,iOS 文件路径都会发生变化

python - socket.bind 方法有什么作用?