项目已编码完毕,要跑正式接口需要修改配置文件中的数据,直接在Windows中打开config.ini文件,修改完成后保存
原打开配置文件代码:
config.read(config_path, encoding='utf-8')
结果:
仔细看这里:
file: ‘D:\Testing\jiaoben\FlychordInterfaceTest\config.ini’, line: 1
‘\ufeff[DATABASE]\n’
\ufeff[DATABASE]\n说明文件开头改变了,可能是我无意中创建了带有BOM(字节顺序标记)的UTF-8文件,而不是普通的UTF-8文件(无BOM)。
我们可以在十六进制编辑器中打开文件并检查第一个字节。
以\xef \xbb \xbf开头的都是这样。
代码优化:
config.read(config_path, encoding='utf-8-sig')
当然,如果你不想去看什么格式的文件,也可以这样写
try:
config.read(config_path, encoding='utf-8')
except Exception:
config.read(config_path, encoding='utf-8-sig')
完整代码:
import os
from FlychordInterfaceTest import getPathInfo
import configparser # 引入我们自己的写的获取路径的类
path = getPathInfo.get_Path() # 调用实例化,path:D:\Testing\jiaoben\FlychordInterfaceTest
config_path = os.path.join(path,'config.ini') # 在path路径下再加一级,configPath:D:\Testing\jiaoben\FlychordInterfaceTest\config.ini
config = configparser.ConfigParser() # 调用外部的读取配置文件的方法
try:
config.read(config_path, encoding='utf-8') # 打开配置文件
except Exception:
config.read(config_path, encoding='utf-8-sig') # 打开配置文件
def get_email(name):
value = config.get("EMAIL", name)
return value
def get_http(name):
value = config.get("HTTP", name)
return value
def get_mysql(name):
value = config.get("DATABASE", name)
return value
print(type(get_http('baseurl')))