1. 程式人生 > >python讀寫檔案中文問題

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)