Python常用模块之configparser模块
生活随笔
收集整理的這篇文章主要介紹了
Python常用模块之configparser模块
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
該模塊適用于配置文件的格式與windows ini文件類似,可以包含一個或多個節(jié)(section),每個節(jié)可以有多個參數(shù)(鍵=值)。
創(chuàng)建文件:
[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes[bitbucket.org] User = hg[topsecret.server.com] Port = 50022 ForwardX11 = nopython生成一個這樣的文檔:
創(chuàng)建文檔
import configparserconfig = configparser.ConfigParser()config["DEFAULT"] = {'ServerAliveInterval': '45','Compression': 'yes','CompressionLevel': '9','ForwardX11':'yes'}config['bitbucket.org'] = {'User':'hg'}config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}with open('example.ini', 'w') as configfile:config.write(configfile)查找文件:
''' 學習中遇到問題沒人解答?小編創(chuàng)建了一個Python學習交流QQ群:725638078 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import configparserconfig = configparser.ConfigParser()#---------------------------查找文件內(nèi)容,基于字典的形式print(config.sections()) # []config.read('example.ini')print(config.sections()) # ['bitbucket.org', 'topsecret.server.com']print('bytebong.com' in config) # False print('bitbucket.org' in config) # Trueprint(config['bitbucket.org']["user"]) # hgprint(config['DEFAULT']['Compression']) #yesprint(config['topsecret.server.com']['ForwardX11']) #noprint(config['bitbucket.org']) #<Section: bitbucket.org>for key in config['bitbucket.org']: # 注意,有default會默認default的鍵print(key)print(config.options('bitbucket.org')) # 同for循環(huán),找到'bitbucket.org'下所有鍵print(config.items('bitbucket.org')) #找到'bitbucket.org'下所有鍵值對print(config.get('bitbucket.org','compression')) # yes get方法取深層嵌套的值增刪改操作:
import configparserconfig = configparser.ConfigParser()config.read('example.ini')config.add_section('yuan')config.remove_section('bitbucket.org') config.remove_option('topsecret.server.com',"forwardx11")config.set('topsecret.server.com','k1','11111') config.set('yuan','k2','22222')config.write(open('new2.ini', "w"))結尾給大家推薦一個非常好的學習教程,希望對你學習Python有幫助!
Python基礎入門教程推薦:更多Python視頻教程-關注B站:Python學習者
Python爬蟲案例教程推薦:更多Python視頻教程-關注B站:Python學習者
總結
以上是生活随笔為你收集整理的Python常用模块之configparser模块的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python常用模块之序列化模块
- 下一篇: Python常用模块之subproces