[Python] python如何在文件中部插入信息

2159 0
王子 2022-11-6 09:17:03 | 显示全部楼层 |阅读模式
目录

    如何在文件中部插入信息实现在文本指定位置插入内容
      1. 场景2. 思路



如何在文件中部插入信息
  1. fp = open('D://代码开发//Python.path//jhp//fadd.txt', 'r')           #指定文件
  2. s = fp.read()                   #将指定文件读入内存
  3. fp.close()                      #关闭该文件
  4. a = s.split('\n')
  5. a.insert(-1, 'a new line')    #在第 LINE+1 行插入
  6. s = '\n'.join(a)                #用'\n'连接各个元素
  7. fp = open('D://代码开发//Python.path//jhp//fadd.txt', 'w')
  8. fp.write(s)
  9. 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文件进行写操作,在指定节点中插入一个属性。如下:
  1. {
  2.     "dataSources":{
  3.         "test_dataSource_hod":{
  4.             "spec":{
  5.                 "dataSchema":{
  6.                     "dataSource":"test_dataSource_hod",
  7.                     "parser":{
  8.                         "type":"string",
  9.                         "parseSpec":{
  10.                             "timestampSpec":{
  11.                                 "column":"timestamp",
  12.                                 "format":"yyyy-MM-dd HH:mm:ss"
  13.                             },
  14.                             "dimensionsSpec":{
  15.                                 "dimensions":[
  16.                                     "method",
  17.                                     "key"
  18.                                 ]
  19.                             },
  20.                             "format":"json"
  21.                         }
  22.                     },
  23.                     "granularitySpec":{
  24.                         "type":"uniform",
  25.                         "segmentGranularity":"hour",
  26.                         "queryGranularity":"none"
  27.                     },
  28.                     "metricsSpec":[
  29.                         {
  30.                             "name":"count",
  31.                             "type":"count"
  32.                         },
  33.                         {
  34.                             "name":"call_count",
  35.                             "type":"longSum",
  36.                             "fieldName":"call_count"
  37.                         },
  38.                         {
  39.                             "name":"succ_count",
  40.                             "type":"longSum",
  41.                             "fieldName":"succ_count"
  42.                         },
  43.                         {
  44.                             "name":"fail_count",
  45.                             "type":"longSum",
  46.                             "fieldName":"fail_count"
  47.                         }
  48.                     ]
  49.                 },
  50.                 "ioConfig":{
  51.                     "type":"realtime"
  52.                 },
  53.                 "tuningConfig":{
  54.                     "type":"realtime",
  55.                     "maxRowsInMemory":"100000",
  56.                     "intermediatePersistPeriod":"PT10M",
  57.                     "windowPeriod":"PT10M"
  58.                 }
  59.             },
  60.             "properties":{
  61.                 "task.partitions":"1",
  62.                 "task.replicants":"1",
  63.                 "topicPattern":"test_topic"
  64.             }
  65.         }
  66.     },
  67.     "properties":{
  68.         "zookeeper.connect":"zookeeper.com:2015",
  69.         "druid.discovery.curator.path":"/druid/discovery",
  70.         "druid.selectors.indexing.serviceName":"druid/overlord",
  71.         "commit.periodMillis":"12500",
  72.         "consumer.numThreads":"1",
  73.         "kafka.zookeeper.connect":"kafkaka.com:2181,kafka.com:2181,kafka.com:2181",
  74.         "kafka.group.id":"test_dataSource_hod_dd"
  75.     }
  76. }
复制代码
需要在最后的properties节点中添加一个"druidBeam.randomizeTaskId":"true"属性。

2. 思路

大概的思路如下:
    扫描文件夹下所有需要更改的文件在文件中确认需要更改的位置插入新的字符
我觉得稍微有点难的地方是在确认插入位置的地方。我们知道的是"druid.selectors.indexing.serviceName":"druid/overlord",这个东西肯定在这个节点中,那我只要能找到这个东西,然后在他的后面 插入就OK了。
好了,思路已经有了,写代码吧。
  1. #!/usr/bin/python
  2. # coding:utf-8
  3. import os
  4. old_string = '"druid/overlord"'
  5. new_string = ('"druid/overlord",' +
  6.               '\n        ' +
  7.               '"druidBeam.randomizeTaskId":"true",')
  8. def insertrandomproperty(file_name):
  9.     if '.json' in file_name:
  10.         with open(file, 'r') as oldfile:
  11.             content = oldfile.read()
  12.             checkandinsert(content, file)
  13.     else:
  14.         pass
  15. def checkandinsert(content, file):
  16.     if 'druidBeam.randomizeTaskId' not in content:
  17.        # to avoid ^M appear in the new file because of different os
  18.        # we replace \r  with ''
  19.         new_content = content.replace(old_string, new_string).replace('\r', '')
  20.         with open(file, 'w') as newfile:
  21.             newfile.write(new_content)
  22.     else:
  23.         pass
  24. if __name__ == '__main__':
  25.     files = os.listdir('/home/tranquility/conf/service_bak')
  26.     os.chdir('/home/tranquility/conf/service_bak')
  27.     for file in files:
  28.         insertrandomproperty(file)
复制代码
就是在内存中更新内容,然后重新写回到文件中。代码只是粗略的表达了思路,可以根据需求继续修改优化。
以上为个人经验,希望能给大家一个参考,也希望大家多多支持中国红客联盟。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行