python 读写json文件

使用json模块:

import json
def main(name):
 #        请在此处添加代码         #
 # *************begin************#
    attribute = []
    ans = []
    
    # try:
    #     print("[",end="")
    #     with open (name,"r") as f:
    #         flag = True
    #         for x in f.readlines():
    #             if flag == True:
    #                 x = x.replace("\n","")
    #                 data = x.split(" ")
    #                 attribute = data
    #                 flag = False
    #             else:
    #                 x = x.replace("\n","")
    #                 data = x.split(" ")

    #                 length = len(attribute)
    #                 s = []
    #                 for x in range(length):
    #                     temp ="'{}': '{}'".format(attribute[x],data[x])
    #                     s.append(temp)
    #                     unit = ", ".join(s)
    #                     unit = "{" + unit + "}"
    #                 ans.append(unit)
    #     print(", ".join(ans),end="")   

    #     print("]",end="")
    # except Exception as e:
    #     print(e)
    try:
        with open (name,'r') as f:
            title = f.readline()
            title = title.replace("\n","").split(" ")
            while True:
                content = f.readline()
                if content == "":break
                content = content.replace("\n","").split(" ")
                temp = dict(zip(title,content))
                ans.append(temp)
                
                
        print(ans)
    except Exception as e:
        print(e)


         
    

 # **************end*************#
        
if __name__ == '__main__':
    name = input()
    main(name)

不使用json模块:

import json
def main(name):
 #        请在此处添加代码         #
 # *************begin************#
    attribute = []
    ans = []
    
    try:
        print("[",end="")
        with open (name,"r") as f:
            flag = True
            for x in f.readlines():
                if flag == True:
                    x = x.replace("\n","")
                    data = x.split(" ")
                    attribute = data
                    flag = False
                else:
                    x = x.replace("\n","")
                    data = x.split(" ")

                    length = len(attribute)
                    s = []
                    for x in range(length):
                        temp ="'{}': '{}'".format(attribute[x],data[x])
                        s.append(temp)
                        unit = ", ".join(s)
                        unit = "{" + unit + "}"
                    ans.append(unit)
        print(", ".join(ans),end="")   

        print("]",end="")
    except Exception as e:
        print(e)
    

 # **************end*************#
        
if __name__ == '__main__':
    name = input()
    main(name)

你可能感兴趣的:(json,开发语言)