繁体   English   中英

如何在文件的精确行中插入列表

[英]How to insert list in a precise line in file

我需要解压缩一个文件夹并更新一个名为“main.py”的文件中的几行。 对于上下文,this.zip 文件将用于创建带有 Terraform 的 Lambda。

我能够解压缩文件夹,并且能够更新“main.py”文件中的代码行(我应用于这些行的更改位于另一个文件“conditions.txt”中。这些更改是NewRelic 策略中某些警报的 ID)。

我的问题是,当我将这些行插入文件时,它们会将 go 插入文件末尾。 即使我确切地知道应该从“main.py”文件的第 8 行开始插入新行(从 20 到 22,取决于“conditions.txt”文件),但我无法做到所以。 我尝试了很多东西,但结果总是一样的。 我觉得我错过了一些东西,我在网上找不到解决方案。

任何建议将不胜感激。

这是我正在运行的 python 代码,之后我包含了“main.py”文件的代码:

import zipfile

# unzip the file in "temp" folder (works fine)
with zipfile.ZipFile("Archive.zip", 'r') as zip_ref:
    zip_ref.extractall("temp")

# delete "payload_" lines that will later be replaced
with open("temp/main.py", "r") as f:
    lines = f.readlines()
with open("temp/main.py", "w") as f:
    for line in lines:

        # if the line in the file does not start with "payload_" its re-writen
        if not line.lstrip().startswith("payload_"):
            f.write(line)


# take "conditions" file and create the text to be inserted in "main.py" inside "temp" folder
conditions = open("conditions.txt").readlines()
condition = ""

new_payload_lines = []

for index, condition in enumerate(conditions):
    index = index + 1
    condition = condition.replace(",", "")
    condition = condition.strip()

    new_payload_lines.append('payload_%s="{\\"query\\":\\"mutation {\\\\n    alertsNrqlConditionStaticUpdate(id: %s, accountId: 11111111, condition: {\\\\n        enabled : true\\\\n      }) {\\\\n        name\\\\n    }\\\\n}\\\\n\\",\\"variables\\":{}}"' % (index, condition))


# This inserts the lines in "new_payload_lines" with proper format, but at the end of the file, which is wrong
with open("temp/main.py", "r+") as f:
    for i, line in enumerate(f):

        if line.startswith("url"):
            f.write("\n")
            for payload in new_payload_lines:
                f.write(payload + "\n")

这是我要修改的文件“main.py”。 您可以看到我需要替换的“payload_x”行:

from ast import For
import requests
import json

url = "https://api.newrelic.com/graphql"


payload_1="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058756, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_2="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058757, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_3="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058758, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_4="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058759, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_5="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058760, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_6="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058761, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_7="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058762, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_8="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058763, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_9="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058764, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_10="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058765, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_11="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058766, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_12="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058767, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_13="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058768, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_14="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058769, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_15="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058770, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_16="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058772, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_17="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058773, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_18="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058774, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_19="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058775, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"
payload_20="{\"query\":\"mutation {\\n    alertsNrqlConditionStaticUpdate(id: 27058776, accountId: 1111111, condition: {\\n        enabled : true\\n      }) {\\n        name\\n    }\\n}\\n\",\"variables\":{}}"

headers = {
  'Content-Type': 'application/json',
  'API-Key': 'AAAA-xxxxxxxxxxxxxxxxxxxxxxx'
}

def lambda_handler(event, context):
  
  payloads = [payload_1,payload_2,payload_3,payload_4,payload_5,payload_6,payload_7,payload_8,payload_9,payload_10,payload_11,payload_12,payload_13,payload_14,payload_15,payload_16,payload_17,payload_18,payload_19,payload_20]
  for ids in payloads:
    response = requests.post(url, headers=headers, data=ids)

  return {
      'statusCode': 200,
      'body': json.dumps('Conditions updated!')
  }

我只是想出了一个解决方案,以防其他人遇到这个问题(它很丑,但它有效)。

我刚刚将 main.py 重命名为 main_new.py 并复制了重命名的文件 main_new_copy.py。 我留下了 main_new.py 的第一部分,我删除了所有 rest,就在我需要放置更新列表的地方。 然后我用 write() 方法将列表放在那里。 在 main_new_copy.py 上,我写了文件的第二部分,也就是我删除的那部分。 然后我加入了这两个文件。 当你有最后期限时,谁需要优雅,哈哈。

这是代码:

import zipfile
import re
import shutil
import os


# unzip the file in "temp" folder (works fine)
with zipfile.ZipFile("Archive.zip", 'r') as zip_ref:
    zip_ref.extractall("temp")


# RENAME FILE BEFORE COPYING IT
old_name = r"temp/main.py"
new_name = r"temp/main_new.py"


os.rename(old_name, new_name)


#COPY MAIN.PY FILE TO THEN COPY THE OTHER HALF OF IT
original = r'temp/main_new.py'
target = r'temp/main_new_copy.py'

shutil.copyfile(original, target)


# delete "payload_" lines that will later be replaced
with open("temp/main_new.py", "r") as f:
    lines = f.readlines()
with open("temp/main_new.py", "w") as f:

    counter = 0

    for line in lines:
        
            # THIS WILL ONLY COPY PORTION OF THE FILE BEFORE THE LIST I NEED TO INSERT
            if not line.lstrip().startswith("payload_") and counter < 7:

                f.write(line)
                counter += 1
                print(counter)
               

# take conditions file and create the text to be inserted in "main.py" inside "temp"

conditions = open("conditions.txt").readlines()

condition = ""

new_payload_lines = []

for index, condition in enumerate(conditions):
    index = index + 1
    condition = condition.replace(",", "")
    condition = condition.strip()

    new_payload_lines.append('payload_%s="{\\"query\\":\\"mutation {\\\\n    alertsNrqlConditionStaticUpdate(id: %s, accountId: 11111111, condition: {\\\\n        enabled : true\\\\n      }) {\\\\n        name\\\\n    }\\\\n}\\\\n\\",\\"variables\\":{}}"' % (index, condition))

# OPEN THE "HALF FILE" I CREATED SO I CAN WRITE THE LIST WHERE I NEED TO
with open("temp/main_new.py", "r+") as f:
    counter = 0
    payloads = old_payloads
    subs = new_payload_lines

    for line in f:

        for payload in new_payload_lines:
            f.write(payload + "\n")

# THIS OPENS THE COPY OF THE NEW FILE AND WRITES THE OTHER HALF
with open("temp/main_new_copy.py", "r") as f:
    lines = f.readlines()
with open("temp/main_new_copy.py", "w") as f:


    for index_2, line in enumerate(lines):
            
            # AT INDEX_2 (LINE) 28 THE TEXT I NEED STARTS, THE UPPER PART OF THE FILE IS NOT COPIED
            if index_2 >= 28:

                f.write(line)
                counter += 1

            else:
                pass

# MERGING THE TWO FILES
data = data2 = ""

with open('temp/main_new.py') as fp:
    data = fp.read()


with open('temp/main_new_copy.py') as fp:
    data2 = fp.read()

data += "\n"
data += data2

with open('temp/main.py', 'w') as fp:
    fp.write(data)

# DELETE THE NEW FILE AND ITS COPY
os.remove('temp/main_new_copy.py')
os.remove('temp/main_new.py')

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM