ini 即 Initialize 初始化之意,通常由节(Section)、键(key)和值(value)组成
ini修改工具
语法
INIFILE filename.ini [section] item=string
- # db.ini 中的内容
- # *********************
- # [localdb]
- # host = 127.0.0.1
- # user = root
- # password = 123456
- # port = 3306
- # database = mysql
- # *********************
- import pymysql
- from configparser import ConfigParser
- cfg = ConfigParser()
- cfg.read("db.ini")
- print(cfg.items("localdb"))
- db_cfg = dict(cfg.items("localdb"))
- print(db_cfg)
- # 端口port类型str转为int
- db_cfg['port'] = int(db_cfg['port'])
- con = pymysql.connect(**db_cfg)
- from pprint import pprint
- lst = [line.strip() for line in open('db.ini')]
- pprint(lst)
http://www.voidspace.org.uk/python/articles/configobj.shtml
https://configobj.readthedocs.io/en/latest/configobj.html
https://pythonhosted.org/theape/documentation/developer/explorations/explore_configobj/basics.html
https://configobj.readthedocs.io/en/latest/configobj.html
https://pythonhosted.org/theape/documentation/developer/explorations/explore_configobj/basics.html
ConfigParser
用户和程序员都使用配置文件。它们通常用于存储应用程序的设置,甚至存储操作系统的设置。Python的核心库包括一个名为configparser的模块
configparser
默认将值以字符串的形式呈现,所以这也就是为什么我们在 db.ini
文件中没有加引号而是直接将字面量写在上面的原因- import configparser
- import os
- def create_config(path):
- """
- Create a config file
- """
- config = configparser.ConfigParser()
- config.add_section("Settings")
- config.set("Settings", "font", "Courier")
- config.set("Settings", "font_size", "10")
- config.set("Settings", "font_style", "Normal")
- config.set("Settings", "font_info",
- "You are using %(font)s at %(font_size)s pt")
- with open(path, "w") as config_file:
- config.write(config_file)
- def get_config(path):
- """
- Returns the config object
- """
- if not os.path.exists(path):
- create_config(path)
- config = configparser.ConfigParser()
- config.read(path)
- return config
- def get_setting(path, section, setting):
- """
- Print out a setting
- """
- config = get_config(path)
- value = config.get(section, setting)
- msg = "{section} {setting} is {value}".format(
- section=section, setting=setting, value=value)
- print(msg)
- return value
- def update_setting(path, section, setting, value):
- """
- Update a setting
- """
- config = get_config(path)
- config.set(section, setting, value)
- with open(path, "w") as config_file:
- config.write(config_file)
- def delete_setting(path, section, setting):
- """
- Delete a setting
- """
- config = get_config(path)
- config.remove_option(section, setting)
- with open(path, "w") as config_file:
- config.write(config_file)
- if __name__ == "__main__":
- path = "settings.ini"
- font = get_setting(path, 'Settings', 'font')
- font_size = get_setting(path, 'Settings', 'font_size')
- update_setting(path, "Settings", "font_size", "12")
- delete_setting(path, "Settings", "font_style")
批量读取ini文件并转存到excel中
- from configobj import ConfigObj
- import csv
- import glob
- import pandas as pd
- with open('data.csv', 'w', newline='', encoding='utf_8_sig') as csvfile:
- list_X=['Name', 'Tax', 'Mac', 'ServerIP', 'DbPath', 'IcCard',
- 'Code', 'Brand', 'Area', 'contactName1', 'post1', 'mobile1',
- 'phone1', 'email1', 'contactName2', 'post2', 'mobile2',
- 'phone2', 'email2', 'KEY', 'DiskNum', 'DiskPwd', 'CertPwd']
- writer = csv.writer(csvfile)
- writer.writerow(list_X)
- for conf_ini in glob.glob(r"D:\日常工作记录\20200601\*.ini"):
- config = ConfigObj(conf_ini, encoding='ANSI', raise_errors=True, list_values=False)
- # print(config.filename)
- # print(dir(config))
- # print(config.dict())
- list_V=[]
- for i in list_X:
- list_V.append(config['CompanyInfo'][i])
- writer.writerow(list_V)
- pd.read_csv('data.csv').to_excel('data.xlsx', index=False)
ConfigObj
http://python101.pythonlibrary.org/chapter30_configobj.html
https://configobj.readthedocs.io/en/latest/index.html
pip install configobj
- import configobj
- def createConfig(path):
- config = configobj.ConfigObj()
- config.filename = path
- config["Sony"] = {}
- config["Sony"]["product"] = "Sony PS3"
- config["Sony"]["accessories"] = ['controller', 'eye', 'memory stick']
- config["Sony"]["retail price"] = "$400"
- config.write()
- if __name__ == "__main__":
- createConfig("config.ini")
- >>> from configobj import ConfigObj
- >>> config = ConfigObj(r"path to config.ini")
- >>> config.filename
- 'config.ini'
- >>> config.dict()
- {'Sony': {'product': 'Sony PS3', 'accessories': ['controller', 'eye', 'memory stick'], 'retail price': '$400'}}
- >>> config.dict()["Sony"]["product"]
- 'Sony PS3'
- >>> config.dict()["Sony"]["accessories"]
- ['controller', 'eye', 'memory stick']
- >>> type(config.dict()["Sony"]["accessories"])
- <type 'list'>
评论
发表评论