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)

即可解决

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值