python讀取配置檔案configparser

2021-08-08 00:14:02 字數 1756 閱讀 3191

可讀取寫入配置檔案

import configparser

import os

import sys

class testcfigparser(object):

config = configparser.configparser()

def get_value(self):

root_dir = os.path.dirname(os.path.abspath('.'))

print(root_dir)

file_path = os.path.dirname(os.path.abspath('.'))+'/config/config.ini' #檔案路徑

self.config.read(file_path) #讀檔案

browser = self.config.get("browsertype","browsername") #key、value型別

url = self.config.get("testserver","url")

for section in self.config.sections(): #嘗試用到section、option

print(section)

for option in self.config.options(section):#k,value section \ option

#print(option)

print(option+'='+self.config.get(section,option)) #get方法get(section,option)

return(browser,url)

def set_value(self):

file_path = os.path.dirname(os.path.abspath('.')) + '/config/config.ini'

self.config.add_section('book')

self.config.set('book','title','標題')

self.config.set('book','author','作者')

self.config.write(sys.stdout)

self.config.write( open(file_path, 'a') )

test = testcfigparser()

print(test.get_value())

test.set_value()

在python 3 中模組名字為configparser首字母小寫,文章 提到一些常用的方法如下

1、config=configparser.configparser()

建立configparser例項

2、config.sections()

返回配置檔案中節序列

3、config.options(section)

返回某個專案中的所有鍵的序列

4、config.get(section,option)

返回section節中,option的鍵值

5、config.add_section(str)

新增乙個配置檔案節點(str)

6、config.set(section,option,val)

設定section節點中,鍵名為option的值(val)

7、config.read(filename)

讀取配置檔案

8、config.write(obj_file)

寫入配置檔案

Python 配置檔案讀取

python提供了configparser包來進行配置檔案讀取。api 所謂的sections就是乙個配置塊。下面是乙個配置檔案db.ini mongo db host 127.0.0.1 db port 27017 system timeout 2000 interval 2000 包含mongo...

python讀取配置檔案

在對pyqt的使用中,很多變數是需要靈活配置的,防止動輒需要修改程式。python提供了configparser模組 配置檔案片段如下 db 資料庫型別 db type mysql,oracle,highgo 片段如下 configfile component.ini cf configparser...

Python 讀取配置檔案

1 配置檔案db config.ini 2 python讀取配置檔案 import configparser 讀取配置檔案 建立乙個管理物件 conf configparser.configparser 配置檔案匯入管理物件,配置檔案內容載入到記憶體中 conf.read db config.ini...