網站首頁 編程語言 正文
如何在文件中部插入信息
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)
就是在內存中更新內容,然后重新寫回到文件中。代碼只是粗略的表達了思路,可以根據需求繼續修改優化。
原文鏈接:https://blog.csdn.net/weixin_42891455/article/details/121952348
相關推薦
- 2022-05-15 uniapp穿透第三方uView組件樣式
- 2022-11-03 ahooks?useVirtualList?封裝虛擬滾動列表_React
- 2022-06-11 C#實現文件Move和Copy操作_C#教程
- 2022-08-25 C++示例講解vector容器_C 語言
- 2022-07-30 jQuery?UI組件介紹_jquery
- 2022-11-23 Android10?Binder原理概述深入解析_Android
- 2023-07-02 jQuery和HTML對某個標簽設置只讀或者禁用屬性的方式_jquery
- 2022-07-10 同時啟動兩個項目,產生的跨域問題
- 最近更新
-
- window11 系統安裝 yarn
- 超詳細win安裝深度學習環境2025年最新版(
- Linux 中運行的top命令 怎么退出?
- MySQL 中decimal 的用法? 存儲小
- get 、set 、toString 方法的使
- @Resource和 @Autowired注解
- Java基礎操作-- 運算符,流程控制 Flo
- 1. Int 和Integer 的區別,Jav
- spring @retryable不生效的一種
- Spring Security之認證信息的處理
- Spring Security之認證過濾器
- Spring Security概述快速入門
- Spring Security之配置體系
- 【SpringBoot】SpringCache
- Spring Security之基于方法配置權
- redisson分布式鎖中waittime的設
- maven:解決release錯誤:Artif
- restTemplate使用總結
- Spring Security之安全異常處理
- MybatisPlus優雅實現加密?
- Spring ioc容器與Bean的生命周期。
- 【探索SpringCloud】服務發現-Nac
- Spring Security之基于HttpR
- Redis 底層數據結構-簡單動態字符串(SD
- arthas操作spring被代理目標對象命令
- Spring中的單例模式應用詳解
- 聊聊消息隊列,發送消息的4種方式
- bootspring第三方資源配置管理
- GIT同步修改后的遠程分支