Pythonはテキスト指定位置にコンテンツを挿入する

16685 ワード

1.シーン
本番環境では、大量のjsonファイルを書き込み、指定したノードに属性を挿入する必要があります.次のようになります.
{
    "dataSources":{
        "test_dataSource_hod":{
            "spec":{
                "dataSchema":{
                    "dataSource":"test_dataSource_hod",
                    "parser":{
                        "type":"string",
                        "parseSpec":{
                            "timestampSpec":{
                                "column":"timestamp",
                                "format":"yyyy-MM-dd HH:mm:ss"
                            },
                            "dimensionsSpec":{
                                "dimensions":[
                                    "method",
                                    "key"
                                ]
                            },
                            "format":"json"
                        }
                    },
                    "granularitySpec":{
                        "type":"uniform",
                        "segmentGranularity":"hour",
                        "queryGranularity":"none"
                    },
                    "metricsSpec":[
                        {
                            "name":"count",
                            "type":"count"
                        },
                        {
                            "name":"call_count",
                            "type":"longSum",
                            "fieldName":"call_count"
                        },
                        {
                            "name":"succ_count",
                            "type":"longSum",
                            "fieldName":"succ_count"
                        },
                        {
                            "name":"fail_count",
                            "type":"longSum",
                            "fieldName":"fail_count"
                        }
                    ]
                },
                "ioConfig":{
                    "type":"realtime"
                },
                "tuningConfig":{
                    "type":"realtime",
                    "maxRowsInMemory":"100000",
                    "intermediatePersistPeriod":"PT10M",
                    "windowPeriod":"PT10M"
                }
            },
            "properties":{
                "task.partitions":"1",
                "task.replicants":"1",
                "topicPattern":"test_topic"
            }
        }
    },
    "properties":{
        "zookeeper.connect":"zookeeper.com:2015",
        "druid.discovery.curator.path":"/druid/discovery",
        "druid.selectors.indexing.serviceName":"druid/overlord",
        "commit.periodMillis":"12500",
        "consumer.numThreads":"1",
        "kafka.zookeeper.connect":"kafkaka.com:2181,kafka.com:2181,kafka.com:2181",
        "kafka.group.id":"test_dataSource_hod_dd"
    }
}

最後のpropertiesノードに"druidBeam.randomizeTaskId":"true"プロパティを追加する必要があります.
2.考え方
大まかな考え方は以下の通りです.
  • フォルダの下にある変更が必要なすべてのファイル
  • をスキャンします.
  • ファイルで変更が必要な場所を確認する
  • 新しい文字を挿入
  • ちょっと難しいところは挿入位置を確認しているところだと思います.私たちが知っているのは"druid.selectors.indexing.serviceName":"druid/overlord",というものがこのノードにあるに違いありません.私はこれを見つけることができて、彼の後ろに挿入すればOKです.はい、考えはもうあります.コードを書きましょう.
    #!/usr/bin/python
    # coding:utf-8
    
    import os
    
    
    old_string = '"druid/overlord"'
    new_string = ('"druid/overlord",' +
                  '
    '
    + '"druidBeam.randomizeTaskId":"true",') def insertrandomproperty(file_name): if '.json' in file_name: with open(file, 'r') as oldfile: content = oldfile.read() checkandinsert(content, file) else: pass 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: newfile.write(new_content) else: pass if __name__ == '__main__': files = os.listdir('/home/tranquility/conf/service_bak') os.chdir('/home/tranquility/conf/service_bak') for file in files: insertrandomproperty(file)

    メモリに内容を更新し、ファイルに書き直します.コードは大まかな考え方を表しているだけで、必要に応じて最適化を修正し続けることができます.