day5_函数_文件读写_用一个函数来满足文件的读或者写_应用默认参数

import json
def op_file_tojson(filename,dic=None): #默认值参数,根据是否传dic字典来判断读还是写
    if dic: #如果dic传了值,不是空的,则往文件里面写
        with open(filename,'w',encoding='utf-8')as fw:
            json.dump(dic,fw)
    else: #如果dic没传值,是空的,则读文件,返回字典
        f = open(filename, encoding='utf-8')
        content = f.read()
        if content:
            res = json.loads(content)
        else:
            res = {}
        f.close()
        return res

猜你喜欢

转载自www.cnblogs.com/once-again/p/9623296.html