Python3-接口自动化-2-生成中文参数写入文件涉及的编码问题

一、问题描述

中文字符写入文件时,存储为乱码

 二、代码如何实现

    def write_potentiall_user_info(self,id_no ,c_name ,c_mobile ):


        config.set("PersonalInformation","id_no",str(id_no))
        config.set("PersonalInformation","c_name",c_name)
        config.set("PersonalInformation","c_mobile",str(c_mobile))

        with open(config_path,"w") as f:

            config.write(f)

三、原因分析

因为我们文件使用UTF-8进行编辑,而Windows默认使用GBK编码格式,所以导致打开文件时出现乱码

四、解决方法

方法一:在打开的文本中解决(治标不治本)。点击图中右下角的UTF-8,选择GBK,在弹出的窗口中选择Reload(重载),再次选择UTF-8,点击Convert

再次写入时仍会存在此问题

方法二:改代码:在打开文本时,设置指定的编码格式 :with open(config_path,"w",encoding="utf-8") as f:

    def write_potentiall_user_info(self,id_no ,c_name ,c_mobile ):


        config.set("PersonalInformation","id_no",str(id_no))
        config.set("PersonalInformation","c_name",c_name)
        config.set("PersonalInformation","c_mobile",str(c_mobile))

        with open(config_path,"w",encoding="utf-8") as f:

            config.write(f)

即可解决

 

原文地址:https://www.cnblogs.com/chushujin/p/12938962.html