![](/img/trans.png)
[英]Trying to write output from shell command to JSON file using python
[英]Python: Replace string in json file, from python shell command
我是python的新手,我正在嘗試做的是用python os shell命令替換json文件中的text / string。 我有點得到我正在尋找的結果,但它附加了額外的空格/在json文件中創建一個新行。 這基本上就是我想要完成的事情:
以下是我目前所擁有的(為了簡單起見,我用簡單的命令替換了真正的aws cli命令)
import os
import fileinput
cmd = 'hostname > host.txt'
cmd2 = 'echo mama > echo.txt'
os.system(cmd)
os.system(cmd2)
file = open('host.txt')
contents = file.read()
with open("out.json", "wt") as fout:
with open("add.json", "rt") as fin:
for line in fin:
fout.write(line.replace('dns',contents))
file2 = open('echo.txt')
contents2 = file2.read()
with open("out2.json", "wt") as fout2:
with open("out.json", "rt") as fin2:
for line in fin2:
fout2.write(line.replace('ip', contents2))
這就是它產生的結果:
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "WildburritoPC
",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "mama
"
}
]
}
}
]
}
正如您所看到的,在Name和Value之后,它確實替換了值,但添加了一個新行並生成了無效的json。
這是我正在替換以下值的文件:
{
"Comment": "A new record set for the zone.",
"Changes": [
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "dns",
"Type": "A",
"TTL": 60,
"ResourceRecords": [
{
"Value": "ip"
}
]
}
}
]
}
提前感謝您的任何答案。 我知道我上面的東西非常臟,而且我確信必須有更好/更清潔的方式來完成我想要做的事情,但最終我知道我們都必須從某個地方開始我甚至無法開始解釋我對這個社區的感激之情,感謝他們迄今提供的所有幫助。
在python的標准庫中有json
模塊,使用它而不是替換字符串會更加錯誤。
要加載json
文件:
import json
with open("add.json", "r") as fout2:
json_data = json.load(fout2)
for change in json_data["Changes"]:
# strip the contents of trailing white spaces (new line)
change["Name"] = change["Name"].strip()
# dump json to another file
with open("out.json", "w") as fout:
fout.write(json.dumps(json_data))
我猜你有這個主意。 json
模塊將注意你的json數據沒有被破壞(或者至少它會在發生這種情況時失敗並且異常)。
只需將該文件作為普通文本文件打開並替換您想要的字符串
with open('file.json', 'r+') as file:
content = file.read()
file.seek(0)
content.replace('string_replaced', 'new_string')
file.write(content)
由於您希望在任何地方替換字符串,因此數據是否為json無關緊要
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.