Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Phân tích file cấu hình INI trong Python với configparser

Giới thiệu về configparser

Module configparser trong thư viện chuẩn của Python cung cấp chức năng đọc và ghi file cấu hình theo định dạng INI (thường dùng trong Windows). File INI bao gồm các section (được bao quanh bởi dấu ngoặc vuông), mỗi section chứa các cặp key/value phân tách bằng = hoặc :, và có thể chứa comment bắt đầu bằng # hoặc ;.

Ví dụ file INI

[Settings]
# Set detailed log for additional debugging info
DetailedLog=1
RunStatus=1
StatusPort=6090
StatusRefresh=10
Archive=1
LogFile=/opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
Version=0.9 Build 4
ServerName=Unknown

[FTP]
RunFTP=1
FTPPort=21
FTPDir=/opt/ecs/mvuser/MV_IPTel/data/FTPdata
UserName=admin
Password=admin

Các phương thức chính của ConfigParser

sections()Trả về danh sách tên các section
has_section()Kiểm tra section có tồn tại
has_option()Kiểm tra option có tồn tại trong section
options()Trả về danh sách option của section
read()Đọc và phân tích file cấu hình
read_file()Đọc từ file object
read_string()Đọc từ chuỗi
read_dict()Đọc từ dictionary
get()Lấy giá trị string
getint()Lấy giá trị integer
getfloat()Lấy giá trị float
getboolean()Lấy giá trị boolean
items()Trả về list tuple (name, value)
remove_section()Xóa section
remove_option()Xóa option
set()Thiết lập option
write()Ghi file INI

Đọc file cấu hình

import configparser

parser = configparser.ConfigParser()
parser.read('sampleconfig.ini')

for sect in parser.sections():
    print('Section:', sect)
    for k, v in parser.items(sect):
        print(' {} = {}'.format(k, v))
    print()

Kết quả

Section: Settings
detailedlog = 1
runstatus = 1
statusport = 6090
statusrefresh = 10
archive = 1
logfile = /opt/ecs/mvuser/MV_IPTel/log/MV_IPTel.log
version = 0.9 Build 4
servername = Unknown

Section: FTP
runftp = 1
ftpport = 21
ftpdir = /opt/ecs/mvuser/MV_IPTel/data/FTPdata
username = admin
password = admin

Tạo file cấu hình mới

import configparser

parser = configparser.ConfigParser()
parser.add_section('Manager')
parser.set('Manager', 'Name', 'Ashok Kulkarni')
parser.set('Manager', 'email', 'ashok@gmail.com')
parser.set('Manager', 'password', 'secret')

with open('test.ini', 'w') as fp:
    parser.write(fp)