跳至主要内容

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...

PDF处理

虚拟pdf打印机 pdfFactory  https://fineprint.com PDFCreator  https://www.pdfforge.org 开源 cutepdf https://www.cutepdf.com/index.htm Doro PDF Writer http://www.the-sz.com/products/doro PdfScribe  https://github.com/stchan/PdfScribe/releases pdf阅读器 Sumatra PDF https://www.sumatrapdfreader.org/ 为什么 Python 用于 PDF 处理  如您所知,PDF 处理属于文本分析。 大多数文本分析库或框架仅使用 Python 设计。 这为文本分析提供了优势。 还有一件事,您永远无法在现有的机器学习或自然语言处理框架中直接处理 pdf。 除非他们为此证明了显式接口。 我们必须先将pdf转换为文本。 我们可以使用下述任何库轻松实现这一点。 在线转换pdf Sejda https://www.sejda.com/pdf-editor 每个文档 200 页的免费限制 https://www.pdf2go.com/ https://tools.pdfforge.org/extract-text PDF24 Tools https://tools.pdf24.org/zh/ 免费且易于使用的在线PDF工具 FreeOCR http://www.paperfile.net/ 适用于Windows的免费光学字符识别软件,支持大多数Twain扫描仪的扫描,还可以打开大多数扫描的PDF和多页Tiff图像以及流行的图像文件格式,FreeOCR输出纯文本,可以直接导出为Microsoft Word格式。 不支持中文 wkhtmltopdf 和 wkhtmltoimage 是使用 QT Webkit 渲染引擎将 HTML 渲染为 PDF 和各种图像格式的命令行工具。这些完全“无头”运行,不需要显示或显示服务。 https://wkhtmltopdf.org/ django-wkhtmltopdf 允许 Django 站点输出动态 PDF。它利用 wkhtmltopdf 库,允许您使用您知道...

安卓 之 apk下载、ADB、 scrcpy

Apk下载 下载离线安装apk https://www.apkmirror.com/ 免费和安全的Android APK下载 https://apkpure.com/ 被暴雷,有植入 https://apps.evozi.com/apk-downloader/ 可以将Google Play( https://play.google.com )中的apk文件所在网址直接下载到台式机和设备上 https://f-droid.org/zh_Hans/ F-Droid 是一个 Android 平台上 FOSS(Free and Open Source Software,自由开源软件)的目录,并提供下载安装支持。使用客户端可以更轻松地浏览、安装及跟进设备上的应用更新。 https://gitlab.com/AuroraOSS/AuroraStore Aurora商店 是Google Play商店的非官方FOSS客户,设计典雅。 Aurora商店不仅下载,更新和搜索Play商店等应用 https://github.com/OpenTracksApp/OpenTracks OpenTracks是一款运动跟踪应用程序,完全尊重您的隐私。 Tasker https://tasker.joaoapps.com/ 是一款适用于Android的应用程序,它可以根据用户定义的配置文件中的上下文、可点击或定时的主屏幕小部件来执行任务。它无需root或特殊的主屏幕就能控制Android设备。 AsciiCam AsciiCam可以从您的相机指向的任何位置实时生成ASCII图像。选择黑白,原色或全彩,拍照,并将其作为图像或HTML共享。您还可以在库中创建ASCII版本的图片,并且每次使用标准相机应用程序拍摄照片时,也可以选择自动生成ASCII版本。 AsciiCam是完全免费和开源的。 Apk1安装器 优化微信apk文件接收体验。 微信收到apk文件会加 ".1" 后缀导致打不开,必须自己手动找到文件重命名去掉后缀。 使用本安装器就可以在微信内,潇洒地点击直接打开。甚至可以在安装器内浏览apk1文件历史接收记录。 ADB ADB全名是 Android Debug Bridge,是开发或使用Android时很常用的工具。可以从电脑通过USB连线到Android手机上 https:...