Python 获取文件夹和文件的JSON树(但仅限于包含给定字符串的文件)

Python 获取文件夹和文件的JSON树(但仅限于包含给定字符串的文件),python,json,file,directory,Python,Json,File,Directory,我需要得到一种JSON格式的过滤目录/文件结构 具体地说,我需要只包含包含给定字符串的文件,并且只包含包含此类文件的目录(在其自身或其某些子体中) 此代码: import os import json def path_to_dict(path): d = {'name': os.path.basename(path)} if os.path.isdir(path): d['type'] = "directory" d['children'] =

我需要得到一种JSON格式的过滤目录/文件结构

具体地说,我需要只包含包含给定字符串的文件,并且只包含包含此类文件的目录(在其自身或其某些子体中)

此代码:

import os
import json

def path_to_dict(path):
    d = {'name': os.path.basename(path)}
    if os.path.isdir(path):
        d['type'] = "directory"
        d['children'] = [path_to_dict(os.path.join(path,x)) for x in os.listdir\
(path)]
    else:
        d['type'] = "file"
    return d

print json.dumps(path_to_dict('.'), indent=2)
从当前目录开始,以我想要的格式为我提供所有目录和文件的漂亮JSON树:

{
    "type": "directory",
    "name": ".",
    "children": [
    {
      "type": "file", 
      "name": "attribute_container.c"
    }, 
    {
      "type": "file", 
      "name": "node.c"
    }, 
    {
      "type": "directory", 
      "name": "power", 
      "children": [
        {
          "type": "file", 
          "name": "clock_ops.c"
        }, 
        {
          "type": "file", 
          "name": "common.c"
        }, 
        {
          "type": "file", 
          "name": "domain.c"
        }, 
        {
          "type": "file", 
          "name": "domain_governor.c"
        }, 
        {
          "type": "file", 
          "name": "generic_ops.c"
        }, 
        {
          "type": "file", 
          "name": "wakeup.c"
        }
      ]
    }, 
    {
      "type": "directory", 
      "name": "regmap", 
      "children": [
        {
          "type": "file", 
          "name": "internal.h"
        }, 
        {
          "type": "file", 
          "name": "Kconfig"
        }, 
        {
          "type": "file", 
          "name": "Makefile"
        }, 
        {
          "type": "file", 
          "name": "regcache-flat.c"
        }, 
        {
          "type": "file", 
          "name": "regmap-spmi.c"
        }, 
        {
          "type": "file", 
          "name": "regmap.c"
        }
      ]
    }, 
    {
      "type": "file", 
      "name": "soc.c"
    }, 
    {
      "type": "file", 
      "name": "syscore.c"
    }, 
    {
      "type": "file", 
      "name": "topology.c"
    }, 
    {
      "type": "file", 
      "name": "transport_class.c"
    }   ] }
但是,我只需要包含给定字符串的文件。此外,只有包含一个或多个此类文件的文件夹,或其某些子体包含此类文件。(可以说,我需要一种“修剪”)

我知道在文件中查找字符串的解决方案:

my_file = ...
my_string = ...
infile = open(my_file,"r")

numlines = 0
found = 0
for line in infile:
    numlines += 1
    found += line.count(my_string)
infile.close()

print "%s was found %i times in %i lines", %string, %found, %numlines
但我很难从问题的顶端将其集成到代码中


非常感谢您的任何提示或建议。

我不想用
os.walk()
重写您的代码。我只想对您的代码做一些小改动

关键是使用None作为sentinel值来修剪文件,并清空
子目录
列表来修剪目录。该实现编写得不好,但它向您展示了如何使用测试的核心

import os
import json

def check_in_file(my_file,my_string):
    with open(my_file) as f:
        try:
            return my_string in f.read()
        except:
            return False

def path_to_dict(path, my_string=None):
    d = {'name': os.path.basename(path)}
    if os.path.isdir(path):
        d['type'] = "directory"
        d['children'] = []
        paths = [os.path.join(path,x) for x in os.listdir(path)]
        #Just the children that contains at least a valid file
        for p in paths:
            c = path_to_dict(p, my_string)
            if c is not None:
                d['children'].append(c)
        if not d['children']:
            return None
    else:
        if my_string is not None and not check_in_file(path,my_string):
            return None
        d['type'] = "file"
    return d

print(json.dumps(path_to_dict('.',), indent=2))
print(json.dumps(path_to_dict('.','kkkkk'), indent=2))

使用os.walk(path)代替对path_to_dict的递归调用。另外,在else之后,在open(path).read()中包含一个if my_字符串:then d['type']=“file”。这将只为包含字符串的文件创建条目。对我来说,代码太棒了。我刚测试了十几个案例。它很有魅力。我花了好几个小时试图想出解决办法,但现在你救了我。非常感谢。该代码将用于C源代码的重要探索性可视化!