[英]How to read dictionary key:value from json file, search the key in a text file and replace the key value through python?
我有一個 JSON 文件:oracle.json
{"Oracle_installation": [{"ORACLE_HOSTNAME": "paulsusm.xxx.com"}]}
現在,我必須在我的 test.py 文件中讀取 JSON 文件值:
import json
with open('D:\oracle.json') as f:
data = json.load(f)
hostname = data['Oracle_installation'][0]['ORACLE_HOSTNAME']
print(hostname)
在 JSON 文件中,key:value 對是: (ORACLE_HOSTNAME, paulsusm.xxx.com)
。 我需要更改另一個文件db.rsp
中的ORACLE_HOSTNAME
值。 我的 python 代碼應該在db.rsp
文件中搜索"ORACLE_HOSTNAME"
字並更改值,該值存儲在 python 的'hostname'
變量中。 如何在 python 中執行此操作?
只需遵循此解決方案,在您的情況下將是:
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)
根據這個答案,您可以使用已經支持就地編輯的fileinput
。 在您的情況下,此代碼將如下所示:
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='')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.