python读写json文件

假如json文件如下

{
    "tep": {},
    "shapes": [
        {
            "label": "pen",
            "points": [
                [
                    1,
                    2
                ],
                [
                    3,
                    4
                ]
            ]
        }
    ],
    "imageHeight": 1536,
    "imageWidth": 2048
}

一个文件夹下都是json文件,**

不废话,看代码

# coding=utf-8
import sys
import time
import os
import numpy as np
import time
import gzip
import datetime
import cv2
import json

class data:
	def __init__(self):
		self.filelist=[]
		self.imglist=[]
		self.dstdir = "D:\\src\\"
		self.srcdir = "D:\\dst\\"
		self.dstfile=""
		self.content=""

	def getfilelist(self , file): 
		for root, dirs, files in os.walk(file):
			for f in files:
				m = os.path.join(root, f)
				ss=os.path.splitext(m)
				print("ss = ",ss)
				dirname = ss[0]#文件夹
				filetype = ss[1]
				print("dirname = ",dirname)
				print("filetype = ",filetype)
				if(filetype == '.json'):
					self.filelist.append(m)
				if(filetype == '.jpg'):
					self.imglist.append(m)


# 修改json文件坐标
	def changefilejson(self):
		for f in self.filelist:			
			srcfilename = os.path.basename(f)#文件名,带后缀
			self.dstfile = self.dstdir+srcfilename
			with open(f,"r") as fhandler:
				self.content = json.loads(fhandler.read())
				# print(self.content)
			t1 = self.content["shapes"][0]["points"][0][0]
			t2 = self.content["shapes"][0]["points"][0][1]
			self.content["shapes"][0]["points"][0][0] = self.content["imageWidth"]-t1
			self.content["shapes"][0]["points"][0][1] = self.content["imageHeight"]-t2

			t1 = self.content["shapes"][0]["points"][1][0]
			t2 = self.content["shapes"][0]["points"][1][1]
			self.content["shapes"][0]["points"][1][0] = self.content["imageWidth"]-t1
			self.content["shapes"][0]["points"][1][1] = self.content["imageHeight"]-t2
			self.content["imageData"]=None
			with open(self.dstfile,"w") as whandler:
				json.dump(self.content, whandler, indent = 4, ensure_ascii=False)
			

def func():
# //1、获取所有文件
# //2、修改文件内容
# //3、写入新文件
	ls = data()
	ls.getfilelist(ls.srcdir)
	ls.changefilejson()

if __name__ == '__main__':
	func()


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值