Python递归地搜索目录,只显示包含特定字符串的文件

2024-05-07 01:07:31 发布

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

我希望递归搜索目录,只显示包含字符串"AWSTemplateFormatVersion"的文件。你知道吗

import os, json

cfn = [".json", ".template", ".yaml", ".yml"]
dir = "./janitor"

def cloudFormation(dir):
    for root, dirs, files in os.walk(dir):
        for file in files:
            if file.endswith(tuple(cfn)):
                with open(os.path.join(root, file), 'r') as fin:
                    data = fin.read()
                    print("************ Break **************")
                    print(data)
                    print(os.path.join(root, file))
    return data

if __name__ == "__main__":
    cloudFormation(dir)

Tags: pathinjsonfordataifosdir
1条回答
网友
1楼 · 发布于 2024-05-07 01:07:31

像这样的怎么样?正如mikemüller在评论中所建议的,测试data中的出现情况。另外,我没有打印lastdata值,而是将您的代码更改为返回条件为true的所有文件的列表:

import os, json

cfn = [".json", ".template", ".yaml", ".yml"]
dir = "./janitor"

def cloudFormation(dir):
    files_with_string = []
    for root, dirs, files in os.walk(dir):
        for file in files:
            if file.endswith(tuple(cfn)):
                with open(os.path.join(root, file), 'r') as fin:
                    data = fin.read()
                    if "AWSTemplateFormatVersion" in data:
                        files_with_string.append(os.path.join(root, file))
                        print("************ Break **************")
                        print(data)
                        print(os.path.join(root, file))
    return files_with_string 

if __name__ == "__main__":
    cloudFormation(dir)

我不知道您希望如何在解决方案中实现它,即文件的数量和大小,但这里有两个注释:

如果您的文件很大,那么可能不是读取整个文件,而是增量地只读取部分文件。你知道吗

如果您有很多文件,那么也许可以创建一个生成器函数,而不是返回所有文件名的列表。你知道吗

相关问题 更多 >