对于每个目录中的每个文件

2024-05-16 12:50:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个程序,搜索特定的文件/扩展名或检查文件本身。 我从“C:\\”开始,我想在子目录中的每个文件上调用这个过程,所以请浏览整个pc文件。我以前使用过os.listdir(),但它不起作用,这段代码行吗

for path, directories, files in os.walk('C:\\'):
        for file in files:
                try:
                       #finding the file
                except: pass

请给我建议更多的方法


Tags: 文件path代码in程序foros过程
2条回答

所有函数都返回文件路径

这将找到第一个匹配项:

import os

def find(name, path="C:\\"):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name)

这将查找所有匹配项:

def find_all(name, path="C:\\"):
    result = []
    for root, dirs, files in os.walk(path):
        if name in files:
            result.append(os.path.join(root, name))
    return result

这将符合一种模式:

import os
import fnmatch

def find(pattern, path="C:\\"):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result

当且仅当您希望到处搜索时,此代码将工作,并且比os.listdir()更高效。 如果除了“只搜索文件”之外,您不需要其他任何东西,os.walk()是最好的选择

相关问题 更多 >