使用python搜索Json目录

时间:2019-06-28 16:11:04

标签: python json directory

我创建了一个Json文件,其中包含特定目录。我正在尝试编写一些东西,使用户可以进入和退出每个“文件夹”,从而创建几乎一个命令行“文件资源管理器”

我的json文件的格式如下:

{
    "children": [
        {
            "children": [
                {
                    "name": "somefile.cmd",
                    "path": "C:\\some\\directory\\somefile.cmd",
                    "type": "file"
                },
                {
                    "name": "otherfile.ps1",
                    "path": "C:\\some\\directory\\somefile.ps1",
                    "type": "file"
                },
                {
                    "name": "somefile.exe",
                    "path": "C:\\some\\directory\\somefile.exe",
                    "type": "file"
                }
            ],
            "name": "somefile",
            "path": "C:\\some\\directory",
            "type": "folder"
        },
        {
            "children": [
.
.
.

我正在使用的功能

def search_json(filename):
    json_file = open(filename)
    data = json.load(json_file)
    subsyst_count = 1
    subsyst_list = []
    #list of subsystems
    for i in data['children']:
        print(subsyst_count, i['name'])
        subsyst_list.append(i['name'])
        subsyst_count = subsyst_count + 1
    user = int(input('Which Subsystem?'))
    #search json for children of subsyst_list[user]
    print(subsyst_list[user])
    for i in data['children']:
        if i['name'] == subsyst_list[user]:
            print(i['name'])
            for j in i['name']:
                print(j[0])

我希望它进入第一个子文件夹,对它下面的所有文件夹进行计数,并提示用户选择要进入哪个子系统的编号。然后,我希望它搜索该新的“子级”子系统目录,并再次编号要进入的文件或要选择的文件。相反,当我有

时,它将引发keyerror
   print(j['name'])

然后,当我拥有以下功能时,该函数将仅拼写子系统的名称:

   print(j['0'])

0 个答案:

没有答案