使用Python读取多个JSON文件

2024-09-30 05:23:48 发布

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

通过以下连接,我试图从多(2)个文件中获取信息。这两个文件都是json格式的。当我说json时,问题发生在关闭时间_数据关闭(),它将关闭两个连接。它支持关闭一个连接,因为我已经缩进了第二个连接。在

请帮忙,刚接触过python和json

import json
from pprint import pprint

json_data=open('/tmp/AutoScale.json')
data = json.load(json_data)

for i in range(len(data["AutoScalingGroups"])):
    pprint(data["AutoScalingGroups"][i]["LaunchConfigurationName"])

#Second Connection

    json_data=open('/tmp/launchConfig.json')
    data = json.load(json_data)
    pprint(data["LaunchConfigurations"][i]["LaunchConfigurationName"])
    json_data.close()      # closed first connection
json_data.close()          # closed second connection

Tags: 文件importjsonclosedata格式时间load
1条回答
网友
1楼 · 发布于 2024-09-30 05:23:48

在for循环中重新分配json_数据时,原始file对象将丢失(实际上,它会丢失所有引用并在python销毁文件时关闭文件)。如果出于某种原因想保留它,则需要在for循环中使用不同的变量。在

这里,我重命名了内部变量。有更好的方法来加载文件(例如,使用with子句,just do data = json.load(open('/tmp/AutoScale.json')),等等。。。但你明白了。在

import json
from pprint import pprint

json_data=open('/tmp/AutoScale.json')
data = json.load(json_data)

for i in range(len(data["AutoScalingGroups"])):
    pprint(data["AutoScalingGroups"][i]["LaunchConfigurationName"])
    json_data_2=open('/tmp/launchConfig.json')
    data_2 = json.load(json_data_2)
    pprint(data_2["LaunchConfigurations"][i]["LaunchConfigurationName"])
    json_data_2.close()      # closed second file
json_data.close()          # closed first file

相关问题 更多 >

    热门问题