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

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程语言 > python >内容正文

python

python中configparser_python中confIgparser模块学习

發(fā)布時(shí)間:2025/3/21 python 38 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python中configparser_python中confIgparser模块学习 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

python中configparser模塊學(xué)習(xí)

ConfigParser模塊在python中用來(lái)讀取配置文件,配置文件的格式跟windows下的ini配置文件相似,可以包含一個(gè)或多個(gè)節(jié)(section), 每個(gè)節(jié)可以有多個(gè)參數(shù)(鍵=值)。使用的配置文件的好處就是不用在程序員寫(xiě)死,可以使程序更靈活。

目錄

三種創(chuàng)建方法

增刪改查

三種創(chuàng)建方法

程序示例:

import configparser

#實(shí)例化出來(lái)一個(gè)類,相當(dāng)于生成一個(gè)空字典

config = configparser.ConfigParser()

#創(chuàng)建也很簡(jiǎn)單,鍵:值

# 值:鍵---值

#第一種方法

config['default']={'IP':'192.168.14.2',

'PORT':'6072'

}

#第二種方法

config['Custom']={}

config['Custom']['User']='admin'

config['Custom']['Password']='123456'

#第三種方法

config['define']={}

Config=config['define']

Config['Host']='192.168.14.2'

Config['Port']='611'

with open('confile','w') as configfile:

#注意這里,是誰(shuí)調(diào)用write方法,是config對(duì)象,不是文件對(duì)象

config.write(configfile)

運(yùn)行結(jié)果:

[default]

ip = 192.168.14.2

port = 6072

[Custom]

user = admin

password = 123456

[define]

host = 192.168.14.2

port = 611

增刪改查

import configparser

config = configparser.ConfigParser()

#讀取配置文件

config.read('confile')

print('獲取文件內(nèi)所有的section:')

print(config.sections())

print('獲得指定section下所有option:')

options=config.options('Custom')

print(options)

print('---------------------------查')

print('獲取指定option下的值:')

value1=config['Custom']['user']

print(value1)

value2=config.get('Custom','user')

print(value2)

# getint(section,option) 得到section中option的值,返回為int類型,還有相應(yīng)的getboolean()和getfloat() 函數(shù)。

print('獲取指定section下所有的鍵值對(duì):')

items = config.items('default')

print(items)

print('遍歷鍵值對(duì):')

for key in config['default']:

print(key)

#下面都會(huì)改變文件,所以最后一步都要重新寫(xiě)入配置文件

print('---------------------------增')

print('添加section:')

# config.add_section('key1')

print('添加鍵值對(duì):')

# config.set('key1','k1','123456')

print('---------------------------改')

#如果需要修改配置文件里面的值,自行打開(kāi)修改

print('---------------------------刪')

print('刪除section:')

config.remove_section('key1')

print('刪除鍵值對(duì):')

config.remove_option('key1','k1')

#重新保存

config.write(open('confile','w'))

總結(jié)

以上是生活随笔為你收集整理的python中configparser_python中confIgparser模块学习的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。