如何在Python中列出目录中的所有文件并将其添加到列表中?


当前回答

这是我的通用函数。它返回文件路径列表而不是文件名,因为我发现这更有用。它有几个可选的参数,使其具有通用性。例如,我经常将其与pattern=“*.txt”或subfolders=True等参数一起使用。

import os
import fnmatch

def list_paths(folder='.', pattern='*', case_sensitive=False, subfolders=False):
    """Return a list of the file paths matching the pattern in the specified 
    folder, optionally including files inside subfolders.
    """
    match = fnmatch.fnmatchcase if case_sensitive else fnmatch.fnmatch
    walked = os.walk(folder) if subfolders else [next(os.walk(folder))]
    return [os.path.join(root, f)
            for root, dirnames, filenames in walked
            for f in filenames if match(f, pattern)]

其他回答

返回绝对文件路径列表,不会递归到子目录

L = [os.path.join(os.getcwd(),f) for f in os.listdir('.') if os.path.isfile(os.path.join(os.getcwd(),f))]

我更喜欢使用glob模块,因为它可以进行模式匹配和扩展。

import glob
print(glob.glob("/home/adam/*"))

它可以直观地进行模式匹配

import glob
# All files and directories ending with .txt and that don't begin with a dot:
print(glob.glob("/home/adam/*.txt")) 
# All files and directories ending with .txt with depth of 2 folders, ignoring names beginning with a dot:
print(glob.glob("/home/adam/*/*.txt")) 

它将返回一个包含查询文件和目录的列表:

['/home/adam/file1.txt', '/home/adam/file2.txt', .... ]

注意,glob忽略以点开头的文件和目录。,因为这些被认为是隐藏的文件和目录,除非模式类似于.*。

使用glob.escape转义不应该是模式的字符串:

print(glob.glob(glob.escape(directory_name) + "/*.txt"))

如果您正在寻找find的Python实现,这是我经常使用的方法:

from findtools.find_files import (find_files, Match)

# Recursively find all *.sh files in **/usr/bin**
sh_files_pattern = Match(filetype='f', name='*.sh')
found_files = find_files(path='/usr/bin', match=sh_files_pattern)

for found_file in found_files:
    print found_file

所以我用它制作了一个PyPI包,还有一个GitHub存储库。我希望有人发现它对这段代码可能有用。

为了获得更好的结果,您可以使用os模块的listdir()方法和生成器(生成器是一个强大的迭代器,可以保持其状态,记得吗?)。以下代码适用于两个版本:Python 2和Python 3。

这里有一个代码:

import os

def files(path):  
    for file in os.listdir(path):
        if os.path.isfile(os.path.join(path, file)):
            yield file

for file in files("."):  
    print (file)

listdir()方法返回给定目录的条目列表。如果给定的条目是文件,则os.path.isfile()方法返回True。yield运算符退出func,但保持其当前状态,并且只返回作为文件检测到的条目的名称。以上所有内容都允许我们对生成器函数进行循环。

def list_files(path):
    # returns a list of names (with extension, without full path) of all files 
    # in folder path
    files = []
    for name in os.listdir(path):
        if os.path.isfile(os.path.join(path, name)):
            files.append(name)
    return files