Python學習---重點模組之configparse

來源:互聯網
上載者:User

標籤:display   fir   class   otto   splay   不能   img   tabs   列印   

configparse模組常用於產生和修改常見的配置文檔

組建組態模組:用字典寫

import configparserconfig = configparser.ConfigParser()config["DEFAULT"] = {‘ServerAliveInterval‘: ‘45‘,                     ‘Compression‘: ‘yes‘,                     ‘CompressionLevel‘: ‘9‘}config[‘USER‘] = {}config[‘USER‘][‘User‘] = ‘hhh‘config[‘SSH‘] = {}topsecret = config[‘SSH‘]topsecret[‘Host Port‘] = ‘50022‘  # mutates the parsertopsecret[‘ForwardX11‘] = ‘no‘  # same hereconfig[‘DEFAULT‘][‘ForwardX11‘] = ‘yes‘with open(‘example.ini‘, ‘w‘) as configfile:    config.write(configfile)

讀取配置:config.sections()

import configparserconfig = configparser.ConfigParser()config.read(‘example.ini‘)                  print(config.sections())                     # [‘USER‘, ‘SSH‘], 預設不dayin[DEFAULT]模組print(config[‘USER‘])                        # <Section: USER>print(config[‘USER‘][‘user‘])                # hgprint(config.defaults())                     # 列印預設模組, 列印出來一個有序的字典print(config.has_section(‘USER‘))            # True OrderedDictprint(config[‘DEFAULT‘][‘compressionlevel‘]) # 9   # 列印預設模組, 列印出來一個有序的字典OrderedDict# 跟字典一樣,只列印key的資訊for key in config[‘DEFAULT‘]:    # print(key, v)  報錯, too many values to unpack (expected 2)    print(key)

刪除整個模組: remove,檔案不能修改,只能覆蓋,可以重新寫入新的檔案

import configparserconfig = configparser.ConfigParser()config.read(‘example.ini‘)# 檔案不能修改,只能覆蓋,可以重新寫入新的檔案config.remove_section(‘SSH‘)with open(‘example.ini‘, ‘w‘, encoding=‘utf-8‘) as f:    config.write(f)print(config.sections())

刪除模組下的某個元素

import configparserconfig = configparser.ConfigParser()config.read(‘example.ini‘)print(config.has_option(‘USER‘, ‘user‘))config.remove_option(‘USER‘, ‘user‘)print(config.has_option(‘USER‘, ‘user‘))with open(‘example.ini‘, ‘w‘, encoding=‘utf-8‘) as f:    config.write(f)

修改配置:

import configparserconfig = configparser.ConfigParser()config.read(‘example.ini‘)print(config[‘USER‘][‘user‘])config.set(‘USER‘, ‘user‘, ‘ftl‘)print(config[‘USER‘][‘user‘])with open(‘example.ini‘, ‘w‘, encoding=‘utf-8‘) as f:    config.write(f)

Python學習---重點模組之configparse

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.