Python implements inserting content in the specified position of text

1. scene

production environment requires writing to a large number of json files, inserting an attribute in the specified node. As follows:

                                "format":"yyyy-MM-dd HH:mm:ss"

needs to be at the end of the properties node to add a "druidBeam. RandomizeTaskId" : "true" property.

2. Ideas

the general idea is as follows:

  1. scan all files to be changed
  2. confirm the position to be changed
  3. insert new character

in the file

where I find it a little bit harder is where I confirm the insertion location. We know is "druid. Selectors. Indexing. The serviceName" : "druid/overlord", this thing must be in the node, that as long as I can find this stuff, and then in his behind with respect to OK.
ok, we've got the idea, let's write the code.

# coding:utf-8

import os

old_string = '"druid/overlord"'
new_string = ('"druid/overlord",' +
              '\n        ' +

def insertrandomproperty(file_name):
    if '.json' in file_name:
        with open(file, 'r') as oldfile:
            content =
            checkandinsert(content, file)


def checkandinsert(content, file):
    if 'druidBeam.randomizeTaskId' not in content:
       # to avoid ^M appear in the new file because of different os
       # we replace \r  with '' 
        new_content = content.replace(old_string, new_string).replace('\r', '')

        with open(file, 'w') as newfile:

if __name__ == '__main__':
    files = os.listdir('/home/tranquility/conf/service_bak')
    for file in files:

is just updating the content in memory, and then rewriting it back to the file. The code is just a rough representation of the idea and can be modified and optimized as needed.

Read More: