python读取json串指定字段-并先清空文件再读写文件

背景:
jsonString.txt中存储了一个json串
目的:
将json串“B”中的人名(StockName字段)提取出来,并写入新的文件jsonElements.txt中。并且每次执行不需要手动清空jsonElements.txt文件。

实现的python代码:

# -*- coding: utf-8 -*-

import json

if __name__ == "__main__":

    # python getElement.py
    # 读取文件相对路径
    input_file = '.\\jsonString.txt'
    output_file = '.\\jsonElements.txt'
    
    with open(input_file, 'r',encoding='utf-8') as fr:
        # 读取整个文件
        dataStr = fr.read()
        # print(dataStr)
        dataDict = json.loads(dataStr) #将json格式转为python字典
        print(dataDict)
        theEle = dataDict['B']
        with open(output_file, 'a', encoding='utf-8') as fw:
            # 先清空文件内容,然后再以‘追加’的形式写文件
            fw.seek(0) # 文件定位到position 0
            fw.truncate() #清空文件
            # 取每个StockName字段
            for x in range(len(theEle)):
                fw.writelines(theEle[x]['StockName'])
                fw.writelines('\n')
    print('Completed...')

truncate() 方法:用于截断文件,如果指定了可选参数 size,则表示截断文件为 size 个字符。 如果没有指定 size,则从当前位置起截断;截断之后 size 后面的所有字符被删除。

为了避免忘记关闭文件,所以使用with open来读文件,加上文件较小,所以使用read()方法。
代码中使用的是相对路径,需要注意执行代码的位置与目标文件位置。

运行结果
python读取json串指定字段-并先清空文件再读写文件_第1张图片

其中jsonString.txt内容如下:

{
     
"A":[
{
     
"CompanyId":"",
"StockName":"黄俊童",
"RealCa":"50",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":"",
"StockName":"杨波",
"RealCa":"50",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":"",
"StockName":"孙有平",
"RealCa":"1",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":"",
"StockName":"余懿强",
"RealCa":"50",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":"",
"StockName":"王淑娟",
"RealCa":"50",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":"",
"StockName":"周可",
"RealCa":"50",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":"",
"StockName":"彭桂林",
"RealCa":"50",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":"",
"StockName":"何涛",
"RealCa":"100",
"CaDate":null,
"Org":0
}
],
"B":[
{
     
"CompanyId":null,
"StockName":"黄俊童",
"RealCa":"50",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":null,
"StockName":"杨波",
"RealCa":"50",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":null,
"StockName":"孙有平",
"RealCa":"1",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":null,
"StockName":"余懿强",
"RealCa":"50",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":null,
"StockName":"佘斯义",
"RealCa":"50",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":null,
"StockName":"佘斯义",
"RealCa":"50",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":null,
"StockName":"何涛",
"RealCa":"100",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":null,
"StockName":"彭桂林",
"RealCa":"50",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":null,
"StockName":"楼新平",
"RealCa":"50",
"CaDate":null,
"Org":0
},
{
     
"CompanyId":null,
"StockName":"王淑娟",
"RealCa":"50",
"CaDate":null,
"Org":0
}
]
}

你可能感兴趣的:(#,文件操作,python,json)