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

问题描述 投票:0回答:8

我使用

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

我需要使用什么功能?

我也看了

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

python file-manager
8个回答
75
投票

需要过滤掉目录;

os.listdir()
列出给定路径中的所有 names。您可以使用
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()
实例
。在常见情况下,这会更快,因为加载的目录已经缓存了足够的信息来确定条目是否是目录:

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


28
投票

这是一个列表理解形式的漂亮的小俏皮话:

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

这将

return
指定的
list
内的
your_directory
文件名。


8
投票
import os
directoryOfChoice = "C:\\" # Replace with a directory of choice!!!
filter(os.path.isfile, os.listdir(directoryOfChoice))

P.S: os.getcwd() 返回当前目录。


7
投票
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

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

0
投票

尽管这是一篇较旧的文章,但为了完整性,请让我添加 3.4 中引入的 pathlib 库,它提供了 OOP 风格的目录和文件处理方式。要获取目录中的所有文件,您可以使用

def get_list_of_files_in_dir(directory: str, file_types: str ='*') -> list:
    return [f for f in Path(directory).glob(file_types) if f.is_file()]

按照您的示例,您可以像这样使用它:

mypath = '/path/to/directory'
files = get_list_of_files_in_dir(mypath)

如果您只需要取决于文件扩展名的文件子集(例如“仅 csv 文件”),您可以使用:

files = get_list_of_files_in_dir(mypath, '*.csv')

0
投票

注意 PEP 471 DirEntry 对象属性是:is_dir(*, follow_symlinks=True)

所以...

from os import scandir
folder = '/home/myfolder/'
for entry in scandir(folder):
    if entry.is_dir():
        # do code or skip
        continue
    myfile = folder + entry.name
    #do something with myfile

    

0
投票

如果你想要一个衬垫Python代码,你可以使用它来提高代码的可读性和美化

只需在代码前添加注释即可,这样在调试时更容易处理。

列出目录中的所有文件过滤文件夹

list_of_files = [file for file in os.listdir(basepath) if not os.path.isdir(os.path.join(basepath, file))]
© www.soinside.com 2019 - 2024. All rights reserved.