python读写文件中文问题

    file = open(fromFilePath,encoding='UTF-8')
    resultFile = open(toFilePath,'w+',encoding='UTF-8')
    try:
        text = file.readlines()
        for line in text:  # 因为text是个List
            jsonText = json.loads(line)  # 将文件中的数据解析出来成为dict数据类型,存储为Unicode形式
            temp_dict = jsonText['institutions']  # 获得institutions对应的dict
            # { "电子科技集团54所" : "石家庄", "西安电子科技大学电子工程学院" : "西安" }
            for key, value in temp_dict.items():
                write_dict = dict()
                if (value == None):
                    write_dict["name"] = key
                    write_dict["location"] = "NoneCity"
                    json_dict = json.dumps(write_dict,ensure_ascii=False)#使用ensure这个属性就得每一个都encode
                    resultFile.write(json_dict+"\n")
                    continue
                write_dict["name"] = key
                write_dict["location"] = value
                #print(type("name".encode('utf-8')))
                json_dict = json.dumps(write_dict,ensure_ascii=False)  # 使用ensure这个属性就得每一个都encode
                resultFile.write(json_dict+"\n")
    finally:
        file.close()
重点是:
resultFile = open(toFilePath,'w+',encoding='UTF-8')
json_dict = json.dumps(write_dict,ensure_ascii=False)

你可能感兴趣的:(Python)