跳至主要内容

python 之 configparser、configobj(ini配置文件)

ini 即 Initialize 初始化之意,通常由节(Section)、键(key)和值(value)组成

ini修改工具




语法
    INIFILE filename.ini [section] item=string



  1. # db.ini 中的内容
  2. # *********************
  3. # [localdb]
  4. # host     = 127.0.0.1
  5. # user     = root
  6. # password = 123456
  7. # port     = 3306
  8. # database = mysql
  9. # *********************
  10.  
  11. import pymysql
  12. from configparser import ConfigParser
  13.  
  14. cfg = ConfigParser()
  15. cfg.read("db.ini")
  16.  
  17. print(cfg.items("localdb"))
  18. db_cfg = dict(cfg.items("localdb"))
  19. print(db_cfg)
  20.  
  21. # 端口port类型str转为int
  22. db_cfg['port'] = int(db_cfg['port'])
  23. con = pymysql.connect(**db_cfg)
  24.  

  1. from pprint import pprint
  2. lst = [line.strip() for line in open('db.ini')]
  3. pprint(lst)




        Python带有一个名为ConfigParser的便捷模块。这对于创建和读取配置文件(即INI文件)非常有用。但是,Michael Foord(《 IronPython in Action》的作者)和Nicola Larosa决定编写自己的配置模块ConfigObj。在许多方面,它是对标准库模块的改进。例如,当它读取配置文件时,它将返回类似于字典的对象。ConfigObj也可以理解某些Python类型。另一个简洁的功能是,您可以创建一个配置规范,ConfigObj将使用该规范来验证配置文件。

ConfigParser
用户和程序员都使用配置文件。它们通常用于存储应用程序的设置,甚至存储操作系统的设置。Python的核心库包括一个名为configparser的模块

configparser 默认将值以字符串的形式呈现,所以这也就是为什么我们在 db.ini 文件中没有加引号而是直接将字面量写在上面的原因


  1. import configparser
  2. import os
  3.  
  4. def create_config(path):
  5.     """
  6.    Create a config file
  7.    """
  8.     config = configparser.ConfigParser()
  9.     config.add_section("Settings")
  10.     config.set("Settings", "font", "Courier")
  11.     config.set("Settings", "font_size", "10")
  12.     config.set("Settings", "font_style", "Normal")
  13.     config.set("Settings", "font_info",
  14.                "You are using %(font)s at %(font_size)s pt")
  15.  
  16.     with open(path, "w") as config_file:
  17.         config.write(config_file)
  18.  
  19.  
  20. def get_config(path):
  21.     """
  22.    Returns the config object
  23.    """
  24.     if not os.path.exists(path):
  25.         create_config(path)
  26.  
  27.     config = configparser.ConfigParser()
  28.     config.read(path)
  29.     return config
  30.  
  31.  
  32. def get_setting(path, section, setting):
  33.     """
  34.    Print out a setting
  35.    """
  36.     config = get_config(path)
  37.     value = config.get(section, setting)
  38.     msg = "{section} {setting} is {value}".format(
  39.         section=section, setting=setting, value=value)
  40.     print(msg)
  41.     return value
  42.  
  43.  
  44. def update_setting(path, section, setting, value):
  45.     """
  46.    Update a setting
  47.    """
  48.     config = get_config(path)
  49.     config.set(section, setting, value)
  50.     with open(path, "w") as config_file:
  51.         config.write(config_file)
  52.  
  53.  
  54. def delete_setting(path, section, setting):
  55.     """
  56.    Delete a setting
  57.    """
  58.     config = get_config(path)
  59.     config.remove_option(section, setting)
  60.     with open(path, "w") as config_file:
  61.         config.write(config_file)
  62.  
  63.  
  64.  
  65. if __name__ == "__main__":
  66.     path = "settings.ini"
  67.     font = get_setting(path, 'Settings', 'font')
  68.     font_size = get_setting(path, 'Settings', 'font_size')
  69.  
  70.     update_setting(path, "Settings", "font_size", "12")
  71.  
  72.     delete_setting(path, "Settings", "font_style")
  73.  


批量读取ini文件并转存到excel中

  1. from configobj import ConfigObj
  2. import csv
  3. import glob
  4. import pandas as pd
  5.  
  6.  
  7. with open('data.csv', 'w', newline='', encoding='utf_8_sig') as csvfile:
  8.     list_X=['Name', 'Tax', 'Mac', 'ServerIP', 'DbPath', 'IcCard',
  9.             'Code', 'Brand', 'Area', 'contactName1', 'post1', 'mobile1',
  10.             'phone1', 'email1', 'contactName2', 'post2', 'mobile2',
  11.             'phone2', 'email2', 'KEY', 'DiskNum', 'DiskPwd', 'CertPwd']
  12.     writer = csv.writer(csvfile)
  13.     writer.writerow(list_X)
  14.     for conf_ini in glob.glob(r"D:\日常工作记录\20200601\*.ini"):
  15.         config = ConfigObj(conf_ini, encoding='ANSI', raise_errors=True, list_values=False)
  16. #         print(config.filename)
  17. #         print(dir(config))
  18. #         print(config.dict())
  19.         list_V=[]
  20.         for i in list_X:          
  21.             list_V.append(config['CompanyInfo'][i])
  22.         writer.writerow(list_V)
  23.  
  24.  
  25. 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


  1. import configobj
  2.  
  3. def createConfig(path):
  4.     config = configobj.ConfigObj()
  5.     config.filename = path
  6.     config["Sony"] = {}
  7.     config["Sony"]["product"] = "Sony PS3"
  8.     config["Sony"]["accessories"] = ['controller', 'eye', 'memory stick']
  9.     config["Sony"]["retail price"] = "$400"
  10.     config.write()
  11.  
  12. if __name__ == "__main__":
  13.     createConfig("config.ini")
  14.  
  15.  
  16. >>> from configobj import ConfigObj
  17. >>> config = ConfigObj(r"path to config.ini")
  18. >>> config.filename
  19. 'config.ini'
  20. >>> config.dict()
  21. {'Sony': {'product': 'Sony PS3', 'accessories': ['controller', 'eye', 'memory stick'], 'retail price': '$400'}}
  22. >>> config.dict()["Sony"]["product"]
  23. 'Sony PS3'
  24. >>> config.dict()["Sony"]["accessories"]
  25. ['controller', 'eye', 'memory stick']
  26. >>> type(config.dict()["Sony"]["accessories"])
  27. <type 'list'>
  28.  

评论

此博客中的热门博文

学习地址

清华大学计算机系课程攻略 https://github.com/PKUanonym/REKCARC-TSC-UHT 浙江大学课程攻略共享计划 https://github.com/QSCTech/zju-icicles https://home.unicode.org/ 世界上的每个人都应该能够在手机和电脑上使用自己的语言。 http://codecanyon.net   初次看到这个网站,小伙伴们表示都惊呆了。原来代码也可以放在网上卖的?!! 很多coder上传了各种代码,每个代码都明码标价。看了下销售排行,有的19刀的卖了3万多份,额di神啊。可以看到代码的演示效果,真的很漂亮。代码以php、wordpress主题、Javascript、css为主,偏前台。 https://www.lintcode.com/ 算法学习网站,上去每天刷两道算法题,走遍天下都不怕。 https://www.codecademy.com/ 包含在线编程练习和课程视频 https://www.reddit.com/ 包含有趣的编程挑战题,即使不会写,也可以查看他人的解决方法。 https://ideone.com/ 在线编译器,可运行,可查看代码示例。 http://it-ebooks.info/ 大型电子图书馆,可即时免费下载书籍。 刷题 https://github.com/jackfrued/Python-100-Days https://github.com/kenwoodjw/python_interview_question 面试问题 https://github.com/kenwoodjw/python_interview_question https://www.journaldev.com/15490/python-interview-questions#python-interpreter HTTP 身份验证 https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Authentication RESTful 架构详解 https://www.runoob.com/w3cnote/restful-architecture.html https://www.rosettacode.org/wiki/Rosetta_C...

MechanicalSoup

用于自动与网站交互的 Python 库。 MechanicalSoup 自动存储和发送 cookie,跟踪重定向,并且可以跟踪链接和提交表单。 它不执行 JavaScript。 https://github.com/MechanicalSoup/MechanicalSoup https://mechanicalsoup.readthedocs.io/en/stable/index.html https://realpython.com/python-web-scraping-practical-introduction/ pip show Mechanicalsoup 找到模块的安装位置 https://stackoverflow.com/questions/54352162/download-file-with-mechanicalsoup # Install dependencies # pip install requests # pip install BeautifulSoup4 # pip install MechanicalSoup # Import libraries import mechanicalsoup import urllib.request import requests from bs4 import BeautifulSoup import re # Create a browser object that can collect cookies browser = mechanicalsoup.StatefulBrowser() browser.open("https://www.ons.gov.uk/economy/grossdomesticproductgdp/timeseries/l2kq/qna") browser.download_link(link_text=".xls",file="D:/ONS_Data.xls" )

安装和卸载软件(msi\exe)

如何判断一个软件是64位的还是32位的? 情况1、 未安装--右键安装程序查看属性,兼容性,勾选兼容模式查看最低适配是vista的是64位,反之32位, 不太准确 情况2、 已安装--运行软件,64位操作系统打开任务管理器看进程后缀名,带*32就是32位,反之64位 https://www.joci.net/xxbk/126251/ FileMon 和 Regmon 不再可供下载。从Windows 2000 SP4,Windows XP SP2,Windows Server 2003 SP1和Windows Vista开始的Windows版本上,它们已被 Process Monitor 取代 https://adamtheautomator.com/procmon/ Process Monitor 是Windows的高级监视工具,它显示实时文件系统,注册表和进程/线程活动。 它结合了两个旧的Sysinternals实用程序 Filemon 和  Regmon的功能 ,并添加了广泛的增强功能列表,包括丰富的和非破坏性的过滤,全面的事件属性(例如会话ID和用户名),可靠的过程信息,带有集成符号的完整线程堆栈支持每个操作,同时记录到文件等。 它独特的强大功能将使Process Monitor成为您的系统故障排除和恶意软件搜索工具包中的核心实用程序。 https://wikileaks.org/ciav7p1/cms/page_42991626.html HKLM\Software\Microsoft\Cryptography\MachineGuid Machine GUID/Cryptography GUID---该密钥通常用作机器的唯一标识符。它也已用于将两台计算机链接在一起-在某些情况下,计算机GUID是与设备(MP3播放器等)一起传递的。 Machine GUID不是唯一 https://docs.microsoft.com/zh-cn/windows/win32/properties/props-system-identity-uniqueid?redirectedfrom=MSDN UniqueID才是唯一 注册表 是存储系统和应用程序的设置信息 打开注册表的方式很简单:cmd中输入regedit 卸载路径只有一个 已安装32位的程序,如果是系统是32位...