配置文件-2

# 使用配置文件
# why :给程序提供一些默认的或个性化的全局参数
# what: 分块kv存储,默认形式有 ini,conf, cfg
# how : configparse, http://devdocs.io/python~3.6/library/configparser
#[DEFAULT]  # section 章节  特殊的章节
import configparser
base_dir = r'D:\python全站'
config = configparser.ConfigParser()
config['DEFAULT'] = {'base_dir':'D:\python全站'}
config_path = os.path.join(base_dir, 'common.ini')
with open(config_path, 'w') as f:
    config.write(f)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-2-9e2c1545cc34> in <module>()
      3 config = configparser.ConfigParser()
      4 config['DEFAULT'] = {'base_dir':'D:\python全站'}
----> 5 config_path = os.path.join(base_dir, 'common.ini')
      6 with open(config_path, 'w') as f:
      7     config.write(f)

NameError: name 'os' is not defined
import configparser
import os
config = configparser.ConfigParser()
config['DEFAULT'] = {'base_dir':'D:\python全站'}
config['DEFAULT']['db_type'] = 'db'
config['DEFAULT']['db_path'] = '${base_dir}/data.db'
config['DEFAULT']['max_items'] = '1000'
config['DEFAULT']['auto_save'] = 'True'

config['coop'] = {}
config['coop']['db_type'] = 'db'
config['coop']['db_path'] = '${base_dir}/data.db'
config_path = os.path.join(base_dir, 'common.ini')
with open(config_path, 'w') as f:
    config.write(f)  # 将f写入到config中?!
config.sections()  # 只显示 coop  方法sections()  DEFAULT的特殊地方,类似于类的继承,现在coop继承了DEFAULT的属性
['coop']
  config['coop']['db_type']  # 如上面所言
'db'
config['coop']['auto_save']  # 配置文件里面都是字符串
'True'
bool(config['coop']['auto_save'])  # 转换
True
for key in config['coop']:  # 继承  printt的是字典的key,而不是里面的子集:字典
    print(key)
db_type
db_path
base_dir
max_items
auto_save
coop = config['coop'] # sections
coop.getboolean('auto_save')   # 获取真的bool值
True
coop.getint('max_items')  # 获取的是整数getint()
1000
coop?
coop.get('db_path')  #字典的方法dic.get()
'${base_dir}/data.db'
config.read(config_path) #config的方法config.read() 读取的是文件
['D:\\python全站\\common.ini']
config.read?
#Signature: config.read(filenames, encoding=None)
Docstring:
Read and parse a filename or a list of filenames.
Files that cannot be opened are silently ignored; this is
designed so that you can specify a list of potential
configuration file locations (e.g. current directory, user's
home directory, systemwide directory), and all existing
configuration files in the list will be read.  A single
filename may also be given.
config.add_section('fang')  # 向config中增加section:config.add_section()
config.set('fang', 'db_name', 'ccoop.pkl') #设置‘fang’的子集
with open(config_path, 'w') as f:
    config.write(f)
config = configparser.ConfigParser(interpolation=configparser.ExtendedInterpolation())
config.read(config_path)   # 获取的是完整的路径
['D:\\python全站\\common.ini']
config['coop']['db_path']  ######\全路径
'D:\\python全站/data.db'
# 面向对象三步走
# 1 规划函数
def write_config():
    pass
def config_read():
    pass
def config_check():
    pass
def add_config():
    pass
# 面向对象三步走
# 1 规划函数
import os
import pickle
import configparser
base_dir = r'D:\python全站'
config_path = os.path.join(base_dir, 'demo.ini')
data = {
    'DEFAULT':{
        'base_dir':'D:\python全站', 'db_type':'db', 'db_path':'${base_dir}/data.db', 'max_items':'1000', 'auto_save':'True'
    },
    'coop':{
        'db_type':'db','db_path':'${base_dir}/data.db'
    }

}
# base_dir = input('please input you base dir:')
# suffix = input('please input your suffix:')
# config_path = os.path.join(base_dir, suffix)
config = configparser.ConfigParser()
def write_config(data:dict):    #必须是dict,四个字母
#     config = configparser.ConfigParser()
    for k, v in data.items():
        config[k] = v
    config_path = os.path.join(base_dir, 'demo.ini')
    with open(config_path, 'w') as f:
        config.write(f)

def config_read(config_path):
    config = configparser.ConfigParser()
    config.read(config_path)
    for k in config.sections():
        for m in config[k]:
            print(m)
#         for m, n in k.items():
#             print(m, n)

#     return config.read(config_path)

def config_check(sect):
    pass
def add_config(sect, k, v):
#     config = configparser.ConfigParser() 
    config.add_section(sect)
    config.set(sect, k, v)
    with open(config_path, 'w') as f:
        config.write(f)

write_config(data)
add_config('fang', 'db_type', 'db')
# coop = config['fang']
# coop['fang']   #config_read()的时候到了
config_read(config_path)
config.sections()  #如何print出所有的demo.db中多有内容
import re
re_gen = re.compile(r'(\n)')
with open(config_path, 'r') as f:
    aa = f.readlines()
    print(aa)
    bb = []
    for i in aa:
        cc = re_gen.sub(' ', i)
        bb.append(cc)
print(bb)
db_type
db_path
base_dir
max_items
auto_save
db_type
base_dir
db_path
max_items
auto_save
['[DEFAULT]\n', 'base_dir = D:\\python全站\n', 'db_type = db\n', 'db_path = ${base_dir}/data.db\n', 'max_items = 1000\n', 'auto_save = True\n', '\n', '[coop]\n', 'db_type = db\n', 'db_path = ${base_dir}/data.db\n', '\n', '[fang]\n', 'db_type = db\n', '\n']
['[DEFAULT] ', 'base_dir = D:\\python全站 ', 'db_type = db ', 'db_path = ${base_dir}/data.db ', 'max_items = 1000 ', 'auto_save = True ', ' ', '[coop] ', 'db_type = db ', 'db_path = ${base_dir}/data.db ', ' ', '[fang] ', 'db_type = db ', ' ']
re_gen.sub?
print?
# 使用configadmin为项目51备忘录扩展功能
#针对上次作业的MemoAdmin类
# 1,添加注册和登陆功能,用户密码使用dict保存为:users.pkl
# 2. 添加配置文件,为备忘录数据指定路径,类型和文件名
#  比如coop,则数据文件可以为coop.pkl或者coop.db
# 3.注册时,相应数据文件根据用户名在配置文件保存为新的section,
# 如coop,则有新的section 叫做[coop]
# 4 .启动程序先提示登陆每次登陆时候,先根据配置文件读取用户信息,找不到,提示注册
class MemoAdmin:
    def __init__(self, config):
        self.config = config

    def register(self):
        pass

    def login(self):
        pass

猜你喜欢

转载自blog.51cto.com/13118411/2143371