0

I have a JSON file: oracle.json

{"Oracle_installation": [{"ORACLE_HOSTNAME": "paulsusm.xxx.com"}]}

Now, I had to read the JSON file values in my test.py file:

import json
with open('D:\oracle.json') as f:
    data = json.load(f)

hostname = data['Oracle_installation'][0]['ORACLE_HOSTNAME']
print(hostname)

In the JSON file, the key:value pair is: (ORACLE_HOSTNAME, paulsusm.xxx.com). I need to change the ORACLE_HOSTNAME value in another file db.rsp. My python code is supposed to search the "ORACLE_HOSTNAME" word in db.rsp file and change the value, which is stored in 'hostname' variable in python. How can I do this in python?

Red
  • 26,798
  • 7
  • 36
  • 58
Susmit
  • 1

1 Answers1

1

Simply follow this solution, which in your case would be:

filename = 'db.rsp'
# Read in the file
with open(filename, 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace("ORACLE_HOSTNAME", hostname)

# Write the file out again
with open(filename, 'w') as file:
  file.write(filedata)

solution 2

And according to this answer you can use fileinput, which already supports inplace editing. In your case this code will look like:

import fileinput

filename = 'db.rsp'
with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace("ORACLE_HOSTNAME", hostname), end='')
Joost Döbken
  • 3,450
  • 2
  • 35
  • 79