0

使用 json 转储我编写了文本文件,然后使用 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()
4

0 回答 0