自定义json

import json


class My_json:   # 定义json类
    def __init__(self, path):  # 初始化方法
        self.file = path

    def dump(self, obj):  # 方法
        with open(self.file, 'a', encoding='utf-8') as f:
            ret = json.dumps(obj)
            f.write(ret + '\n')

    def load(self):
        with open(self.file, 'r', encoding='utf-8') as f:
            while 1:
                try:
                    for i in f:
                        yield json.loads(i.strip())
                except EOFError:
                    break


obj = My_json('json_file')  # 在同一目录下传入文件名
obj.dump([1, 2, 3])
for i in obj.load():
    print(i)

  

猜你喜欢

转载自www.cnblogs.com/biu-py/p/10977158.html