我知道标题可能不太清楚,所以我的问题如下: 我对Python非常陌生,我有一个yaml文件,其中包含许多类似于这组代码的内容:
x-amazon-apigateway-integration:
responses:
default:
statusCode: "200"
uri: addProfile_uri
passthroughBehavior: when_no_match
httpMethod: POST
cacheNamespace: roq9wj
cacheKeyParameters:
- method.request.path.proxy
type: aws_proxy
x-amazon-apigateway-integration:
responses:
default:
statusCode: "200"
uri: deleteProfile_uri
passthroughBehavior: when_no_match
httpMethod: POST
cacheNamespace: roq9wj
cacheKeyParameters:
- method.request.path.proxy
type: aws_proxy
以及包含以下内容的json文件:
[
{
"function_variable_uri_name": "addProfile_uri",
"uri": "arn:aws:apigateway:XXXXXX"
},
{
"function_variable_uri_name": "deleteProfile_uri",
"uri": "arn:aws:apigateway:XXXXXX"
},
{
"function_variable_uri_name": "getAllProfile_uri",
"uri": "arn:aws:apigateway:XXXXXX"
},
{
"function_variable_uri_name": "getProfile_uri",
"uri": "arn:aws:apigateway:XXXXXX"
},
{
"function_variable_uri_name": "updateProfile_uri",
"uri": "arn:aws:apigateway:XXXXXX"
}
]
因此,在我的Python代码中,我尝试在JSON文件中循环,提取uri
和function_variable_uri_name
值。其思想是在yaml文件内循环并搜索function_variable_uri_name
(例如:deleteProfile_uri
)的每一次出现,并使用uri
值arn:aws:apigateway:XXXXXX
对其进行更改
import json
flambda = open('uri_var.json')
lambda_inputs = json.load(flambda)
fout = open("profile_modif.yaml", "wt")
with open('profile.yaml', 'r+') as file:
for each in lambda_inputs:
variable_uri_name = each['function_variable_uri_name']
uri = each['uri']
for line in file:
fout.write(line.replace(variable_uri_name, uri))
file.close()
我上面的Python代码只将YAML中第一次出现的variable_uri_name
的值addProfile_uri
更改为uri
的值,而不更改deleteProfile_uri
,我需要JSON文件中的for循环,因为我有许多输入需要处理
更新:下面是我的json文件中function_variable_uri_name
和uri
两个值的简单打印:
addProfile_uri
arn:aws:apigateway:XXXXXX
deleteProfile_uri
arn:aws:apigateway:XXXXXX
getAllProfile_uri
arn:aws:apigateway:XXXXXX
getProfile_uri
arn:aws:apigateway:XXXXXX
updateProfile_uri
arn:aws:apigateway:XXXXXX
有什么解决办法吗?提前谢谢大家
改变你对工作的想法。您希望在每一行上工作一次,并在每一行上执行多个检查和替换操作。换句话说,您希望先对文件进行迭代,然后在文件操作的嵌套操作中对替换变量进行迭代:
相关问题 更多 >
编程相关推荐