一,首先得了解ini配置文件的格式:UTF-16 LE,(打开文本就能看),
其对应的编码格式:这里是做判断文件的编码并对应使用utf-16/32(每个人的需求会不一样,参考就好了)
self.encoding = self.determine_encoding(self.file_path) if self.encoding == 'utf-16-le' or self.encoding == 'utf-16-be': self.cf.read(self.file_path, encoding='utf-16') # 读取文件,返回列表 elif self.encoding == 'utf-32-le' or self.encoding == 'utf-32-be': self.cf.read(self.file_path, encoding='utf-32') else: self.cf.read(self.file_path, encoding=self.encoding)
二,得了解python对配置文件操作的方法:ConfigParser模块
其对应有三个方法(感兴趣去做了解):
RawConfigParser()
ConfigParser()
SafeConfigParser()
常用的也就是ConfigParser(),RawConfigParser()的话,区别在于ConfigParser()对于配置文件中含%读取时会报错,python会报只读%%的问题,问题就在于ConfigParser(),对此网上有解释。
RawConfigParser()这时就派上用途,可以将vlaue中含%%的数值提取出来,整体功能与ConfigParser()相差也不大,想了解具体就百度,
三,对应的方法:(demo)
import configparser import os curpath = os.path.dirname(os.path.realpath(__file__)) # 当前文件路径 inipath = os.path.join(curpath, "jx_request_log.ini") # 配置文件路径(组合、相对路径) conf = configparser.ConfigParser() # configparser.RawConfigParser() conf.read(inipath, encoding="utf-16") conf.set('DoLoadInfo', 'method', '44444') conf.set('stat.htm', "t", 'revise_t[0]') conf.set('stat.htm', "r", "None") conf.write(open(inipath, "w+", encoding="utf-16"))
详细点的方法有个好一点的链接: python读写增删修改ini配置文件 - 万雨 - 博客园 (cnblogs.com)
注意一下上面几处点基本没啥问题了,还有一点就是有时候修改ini文件时会导致编码格式转换成utf-8,具体原因我还没去深入挖掘,出错时注意一下是不是文件格式变了,