Django如何使用ini网站配置文件?
1。 .ini文件说明
格式如下:
;comments#
[section1]
Param1 = value1
Param2= value2
[section2]
Param3= value3
Param4= value4
;注意
==[section]== 代表一个模块。一个文件中可以设置多个模块,并且可以自定义模块名称
Param1 = value1 参数名和参数值,键值对形式
我的配置文件内容是:
conf.conf ini
;设置语言
[lan]
language = Chinese
2. 所需模块
import os
import configparser
3. 读取操作
proDir = os.path.dirname(os.path.realpath(sys.argv[0]))
configPath = os.path.join(proDir,"conf.ini")#获取配置文件的路径
conf=configparser.ConfigParser()#创建对象用于对配置文件进行操作
conf.read(configPath,encoding="utf-8-sig")#以utf8编码形式读取
try:
lan = conf.get("lan","language") #读取配置文件设置的语言的值
except:
lan = "English"
相关读取方法:
read(filename):读取文件内容
sections():获取所有节并以列表的形式返回。
options(section):获取该section的所有选项。
items(section):检索此部分中的所有键值对。
get(section,option):获取section中option的值,返回字符串类型。
tinted(section,option):获取section中option的值,返回int类型。
4。写入操作
# 修改配置文件中的语言
conf.set("lan","language","Chinese") #设置"lan"模块下的"language"的值为"Chinese"
conf.write(open(configPath,'w+',encoding="utf-8-sig")) #将修改写入到配置文件
相关写入方法:
write(fp):将配置对象写入ini格式文件。
add_section(section):添加新部分。
set(section, option, value):设置section中的选项,需要调用write将内容写入配置文件。
remove_section(section):删除一个部分。
remove_option(section,option):删除某个section下的选项
5.注意细节
1.如果配置文件无法读取(不存在),则创建一个新的安.
#判断是否存在配置文件,没有则创建
if os.path.exists(configPath) == False:
conf['lan'] = {'language':'English'}
with open('conf.ini','w',encoding="utf-8-sig") as configfile:
conf.write(configfile)
2。如果有中文字符,编码应设置为UTF8。
conf.read(configPath,encoding="utf-8-sig") #注意是“utf-8-sig”
版权声明
本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。