Python內建模組之configparse

2022-05-01 10:12:08 字數 3078 閱讀 8056

configparse 主要是用來處理類似於windows的 ini檔案,這個檔案的特點是有多個節(section),每個節下會儲存多個k=v的值

如下配置

[hardware]

cpu = 2[os]

os =centos

os_version = 6.9kernel_version = 2.6.32[common]

selinux =disabled

file_descriptor = 65535[nginx]

version = 1.6.3install_path = /tuike/server/nginx

config_file =['

/middleware/nginx/centralapi.conf

','/middleware/nginx/wezhuanba1.conf']

import

configparser

config = configparser.configparser() #

得到乙個物件

config["

hardware

"] = #

增加乙個hardware節,節內的內容使用字典資料格式表示

config["

os"] =

config[

'common

'] =

config[

'nginx

'] =

with open(

'test

','w

',encoding='

utf-8

') as f:

config.write(f)

import

configparser

config = configparser.configparser() #

拿到乙個配置物件

############## sections 操作

#判斷sections是否再配置檔案裡

print('os'

in config) #

section in 配置物件

print('

wangys'in

config)

#檢視sections

print(config.sections()) #

直接看sections,因為沒有讀取配置檔案,所以會返回乙個空列表#

config.read('

test.ini

',encoding='

utf-8

') #

讀取配置檔案,注意編碼

print(config.sections()) #

再次列印sections,可以看到有結果

#['hardware', 'os', 'common', 'nginx']

#增加乙個section

config.add_section('

wangys')

print

(config.sections())

#['hardware', 'os', 'common', 'nginx', 'wangys']

#刪除乙個section

config.remove_section('

wangys')

print

(config.sections())

#['hardware', 'os', 'common', 'nginx']

##### 操作k/v

#檢視某個節裡的內容

#使用 for 迴圈去key

#判斷某個key是否再selections裡

for key in config['os'

]:

print

(key)

#options檢視selctions下配置的key

print(config.options('

nginx'))

#檢視你k v 值 返回乙個列表,沒有k/v組成乙個元祖

print(config.items('

nginx'))

#[('version', '1.6.3'), ('install_path', '/tuike/server/nginx'), ('config_file', "['/middleware/nginx/centralapi.conf', '/middleware/nginx/wezhuanba1.conf']")]

#獲取某個節下的某個key的value值

print(config.get('

os','

os_version'))

#print(config['os']['os_version','kernel_version'])

#讀取某個sections下的所有的k/v值

l = config.options('

nginx')

for key in

l:

print('

%s:%s

'%(key,config.get('

nginx

',key)))

#刪除乙個sections下的key

config.remove_option('os

','kernel_version')

print(config.options('os'

))#['os', 'os_version']

#增加乙個option

config.set('

os','

name

','王誠')

print(config.options('os'

))print(config.get('

os','

name'))

#['os', 'os_version', 'name']

#王永勝

with open(

'test.ini

','w

',encoding='

utf-8

') as f:

config.write(f)

python內建模組之random模組

import random print random.random 隨機 0 1 浮點數 print random.uniform 1,10 隨機指定範圍的浮點數 print random.randint 1,3 隨機整數1 3,包括3 print random.randrange 1,3 1 3隨...

python內建模組之XML模組

xml和json 一樣都是可以跨平台的,只是xml相比較,老一點 import xml.etree.elementtree as et a et.parse first xml.xml 載入乙個檔案 root a.getroot print root 乙個xml檔案 print root.tag x...

python內建模組之re模組

在python要想使用正則必須借助於模組,re就是其中之一 查詢字串中所有匹配到的字元,並返回乙個列表,沒有匹配資料則返回乙個空列表 import re re.findall 正規表示式 帶匹配的文字 根據正則匹配除所有符合條件的資料 res re.findall b eva jason jacks...