如何在不使用Python添加新行的情况下更改循环中文件中的行的值?

2024-05-16 11:36:55 发布

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

我知道标题可能不太清楚,所以我的问题如下: 我对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文件中循环,提取urifunction_variable_uri_name值。其思想是在yaml文件内循环并搜索function_variable_uri_name(例如:deleteProfile_uri)的每一次出现,并使用uriarn: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_nameuri两个值的简单打印:

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

有什么解决办法吗?提前谢谢大家


Tags: 文件代码nameawsjsonyamlfunctionuri
1条回答
网友
1楼 · 发布于 2024-05-16 11:36:55

改变你对工作的想法。您希望在每一行上工作一次,并在每一行上执行多个检查和替换操作。换句话说,您希望先对文件进行迭代,然后在文件操作的嵌套操作中对替换变量进行迭代:

import json

with open('uri_var.json') as flambda:
    lambda_inputs = json.load(flambda)

with open("profile_modif.yaml", "wt") as fout:
    with open('profile.yaml', 'r+') as file:
        for line in file:
            for item in lambda_inputs:
                line = line.replace(item['function_variable_uri_name'], item['uri'])
            fout.write(line)

相关问题 更多 >