python如何在文件中部插入信息
如何在文件中部插入信息
fp = open('D://代碼開發(fā)//Python.path//jhp//fadd.txt', 'r') #指定文件 s = fp.read() #將指定文件讀入內(nèi)存 fp.close() #關(guān)閉該文件 a = s.split('\n') a.insert(-1, 'a new line') #在第 LINE+1 行插入 s = '\n'.join(a) #用'\n'連接各個元素 fp = open('D://代碼開發(fā)//Python.path//jhp//fadd.txt', 'w') fp.write(s) fp.close()
結(jié)果:
"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
}
實現(xiàn)在文本指定位置插入內(nèi)容
1. 場景
生產(chǎn)環(huán)境需要對大量的json文件進行寫操作,在指定節(jié)點中插入一個屬性。如下:
{ "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節(jié)點中添加一個"druidBeam.randomizeTaskId":"true"屬性。
2. 思路
大概的思路如下:
- 掃描文件夾下所有需要更改的文件
- 在文件中確認需要更改的位置
- 插入新的字符
我覺得稍微有點難的地方是在確認插入位置的地方。我們知道的是"druid.selectors.indexing.serviceName":"druid/overlord",這個東西肯定在這個節(jié)點中,那我只要能找到這個東西,然后在他的后面 插入就OK了。
好了,思路已經(jīng)有了,寫代碼吧。
#!/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)
就是在內(nèi)存中更新內(nèi)容,然后重新寫回到文件中。代碼只是粗略的表達了思路,可以根據(jù)需求繼續(xù)修改優(yōu)化。
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
詳談在flask中使用jsonify和json.dumps的區(qū)別
下面小編就為大家分享一篇詳談在flask中使用jsonify和json.dumps的區(qū)別,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-03-03深入理解python?生成器、迭代器、動態(tài)新增屬性及方法
這篇文章主要介紹了python?生成器、迭代器、動態(tài)新增屬性及方法,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2023-04-04通過mod_python配置運行在Apache上的Django框架
這篇文章主要介紹了通過mod_python配置運行在Apache上的Django框架,Django是最具人氣的Python web開發(fā)框架,需要的朋友可以參考下2015-07-07tensorflow 恢復指定層與不同層指定不同學習率的方法
今天小編就為大家分享一篇tensorflow 恢復指定層與不同層指定不同學習率的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-07-07使用Python的pencolor函數(shù)實現(xiàn)漸變色功能
這篇文章主要介紹了使用Python的pencolor函數(shù)實現(xiàn)漸變色功能,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-03-03Python機器學習入門(三)之Python數(shù)據(jù)準備
這篇文章主要介紹了Python機器學習入門知識,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-08-08