我需要使用JSON将嵌套Python字典写入文本文件,文本文件将被视为C++字典(使用OpenFo沫)。

2024-04-27 08:20:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用json dump编写了文本文件,然后使用python读写循环删除了双引号和冒号,但是我仍然必须为每个键值添加分号,我不知道该怎么做。有谁能建议最好的方法是什么

这就是字典(python)的样子

fvSolution={"FoamFile":{
                "version"  :    "2.0",
                "class"    : "dictionary",
            },
             "solvers":{
                "p" : {
                    "solver" :"PCG",
                    "preconditioner" :"DIC",
                    "tolerance" :1e-06,
                    "relTol" :0.01
                    }
                }
            }

这就是文本文件的样子,我需要将我的字典转换成这个

FoamFile
{
    version 2.0;
    class   dictionary;
    format  ascii;
}
solvers
{
    p
    {
        solver           PCG;
        preconditioner   DIC;
        tolerance        1e-06;
        relTol           0.01
    }
}

这是我的密码:

# -*- coding: utf-8 -*-
"""
Created on Mon May 11 21:22:59 2020

@author: kundan
"""


import json 

#dictionary sample
fvSolution={
"FoamFile":{ 
"object" : "fvSolution" 
}, 
"solvers" :{ 
    "p" :{ 
        "solver" :"PCG", 
        } 
    } 
} 

#json object
a=json.dumps(fvSolution, indent=4, separators=("","\t")) 

#write json dump to afile
with open("fvSolution", "w") as outfile: 
    outfile.write(a) 

#read the file exported in previous step
f = open("fvSolution", "r") 
lines = f.readlines() 
f.close()

#write the dictionary after replace method
f=open("fvSolution","w") 
for line in lines: 
    line = line.replace('"', '') 
    f.write(line) 
f.close()

Tags: jsondictionary字典versionlineopendumpwrite