首頁 > 軟體

python如何在檔案中部插入資訊

2022-11-03 14:02:00

如何在檔案中部插入資訊

fp = open('D://程式碼開發//Python.path//jhp//fadd.txt', 'r')           #指定檔案
s = fp.read()                   #將指定檔案讀入記憶體
fp.close()                      #關閉該檔案
a = s.split('n')
a.insert(-1, 'a new line')    #在第 LINE+1 行插入
s = 'n'.join(a)                #用'n'連線各個元素
fp = open('D://程式碼開發//Python.path//jhp//fadd.txt', 'w')
fp.write(s)
fp.close()

結果:

"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"
a new line
    }

實現在文字指定位置插入內容

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",' +
              'n        ' +
              '"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)

就是在記憶體中更新內容,然後重新寫回到檔案中。程式碼只是粗略的表達了思路,可以根據需求繼續修改優化。

以上為個人經驗,希望能給大家一個參考,也希望大家多多支援it145.com。


IT145.com E-mail:sddin#qq.com