簡單介紹python如何在檔案中部插入資訊

大雄45發表於2023-04-16
導讀 這篇文章主要介紹了python如何在檔案中部插入資訊問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
如何在檔案中部插入資訊
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)

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

原文來自:


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69955379/viewspace-2945098/,如需轉載,請註明出處,否則將追究法律責任。

相關文章