日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

Python常用模块之configparser模块

發布時間:2025/3/20 python 17 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Python常用模块之configparser模块 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

該模塊適用于配置文件的格式與windows ini文件類似,可以包含一個或多個節(section),每個節可以有多個參數(鍵=值)。

創建文件:

[DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes[bitbucket.org] User = hg[topsecret.server.com] Port = 50022 ForwardX11 = no

python生成一個這樣的文檔:

創建文檔

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)

查找文件:

''' 學習中遇到問題沒人解答?小編創建了一個Python學習交流QQ群:725638078 尋找有志同道合的小伙伴,互幫互助,群里還有不錯的視頻學習教程和PDF電子書! ''' import configparserconfig = configparser.ConfigParser()#---------------------------查找文件內容,基于字典的形式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循環,找到'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模块的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。