Python使用configparser方法如何實現對配置文件進行讀寫?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。
Python自身提供了一個Module - configparser,來進行對配置文件的讀寫
Configuration file parser.
A configuration file consists of sections, lead by a “[section]” header,
and followed by “name: value” entries, with continuations and such in
the style of RFC 822.
Note The ConfigParser module has been renamed to configparser in Python 3. The 2to3 tool will automatically adapt imports when converting your sources to Python 3.
在py2中,該模塊叫ConfigParser,在py3中把字母全變成了小寫。本文以py3為例
類
ConfigParser的屬性和方法
ConfigParser -- responsible for parsing a list of configuration files, and managing the parsed database. methods: __init__(defaults=None, dict_type=_default_dict, allow_no_value=False, delimiters=('=', ':'), comment_prefixes=('#', ';'), inline_comment_prefixes=None, strict=True, empty_lines_in_values=True, default_section='DEFAULT', interpolation=<unset>, converters=<unset>): Create the parser. When `defaults' is given, it is initialized into the dictionary or intrinsic defaults. The keys must be strings, the values must be appropriate for %()s string interpolation. When `dict_type' is given, it will be used to create the dictionary objects for the list of sections, for the options within a section, and for the default values. When `delimiters' is given, it will be used as the set of substrings that divide keys from values. When `comment_prefixes' is given, it will be used as the set of substrings that prefix comments in empty lines. Comments can be indented. When `inline_comment_prefixes' is given, it will be used as the set of substrings that prefix comments in non-empty lines. When `strict` is True, the parser won't allow for any section or option duplicates while reading from a single source (file, string or dictionary). Default is True. When `empty_lines_in_values' is False (default: True), each empty line marks the end of an option. Otherwise, internal empty lines of a multiline option are kept as part of the value. When `allow_no_value' is True (default: False), options without values are accepted; the value presented for these is None. When `default_section' is given, the name of the special section is named accordingly. By default it is called ``"DEFAULT"`` but this can be customized to point to any other valid section name. Its current value can be retrieved using the ``parser_instance.default_section`` attribute and may be modified at runtime. When `interpolation` is given, it should be an Interpolation subclass instance. It will be used as the handler for option value pre-processing when using getters. RawConfigParser objects don't do any sort of interpolation, whereas ConfigParser uses an instance of BasicInterpolation. The library also provides a ``zc.buildbot`` inspired ExtendedInterpolation implementation. When `converters` is given, it should be a dictionary where each key represents the name of a type converter and each value is a callable implementing the conversion from string to the desired datatype. Every converter gets its corresponding get*() method on the parser object and section proxies. sections() Return all the configuration section names, sans DEFAULT. has_section(section) Return whether the given section exists. has_option(section, option) Return whether the given option exists in the given section. options(section) Return list of configuration options for the named section. read(filenames, encoding=None) Read and parse the iterable of named configuration files, given by name. A single filename is also allowed. Non-existing files are ignored. Return list of successfully read files. read_file(f, filename=None) Read and parse one configuration file, given as a file object. The filename defaults to f.name; it is only used in error messages (if f has no `name' attribute, the string `<???>' is used). read_string(string) Read configuration from a given string. read_dict(dictionary) Read configuration from a dictionary. Keys are section names, values are dictionaries with keys and values that should be present in the section. If the used dictionary type preserves order, sections and their keys will be added in order. Values are automatically converted to strings. get(section, option, raw=False, vars=None, fallback=_UNSET) Return a string value for the named option. All % interpolations are expanded in the return values, based on the defaults passed into the constructor and the DEFAULT section. Additional substitutions may be provided using the `vars' argument, which must be a dictionary whose contents override any pre-existing defaults. If `option' is a key in `vars', the value from `vars' is used. getint(section, options, raw=False, vars=None, fallback=_UNSET) Like get(), but convert value to an integer. getfloat(section, options, raw=False, vars=None, fallback=_UNSET) Like get(), but convert value to a float. getboolean(section, options, raw=False, vars=None, fallback=_UNSET) Like get(), but convert value to a boolean (currently case insensitively defined as 0, false, no, off for False, and 1, true, yes, on for True). Returns False or True. items(section=_UNSET, raw=False, vars=None) If section is given, return a list of tuples with (name, value) for each option in the section. Otherwise, return a list of tuples with (section_name, section_proxy) for each section, including DEFAULTSECT. remove_section(section) Remove the given file section and all its options. remove_option(section, option) Remove the given option from the given section. set(section, option, value) Set the given option. write(fp, space_around_delimiters=True) Write the configuration state in .ini format. If `space_around_delimiters' is True (the default), delimiters between keys and values are surrounded by spaces.
配置文件的數據格式
下面的config.ini展示了配置文件的數據格式,用中括號[]括起來的為一個section例如Default、Color;每一個section有多個option,例如serveraliveinterval、compression等。
option就是我們用來保存自己數據的地方,類似于鍵值對 optionname = value 或者是optionname : value (也可以設置允許空值)
[Default] serveraliveinterval = 45 compression = yes compressionlevel = 9 forwardx11 = yes values like this: 1000000 or this: 3.14159265359 [No Values] key_without_value empty string value here = [Color] isset = true version = 1.1.0 orange = 150,100,100 lightgreen = 0,220,0
數據類型
在py configparser保存的數據中,value的值都保存為字符串類型,需要自己轉換為自己需要的數據類型
Config parsers do not guess datatypes of values in configuration files, always storing them internally as strings. This means that if you need other datatypes, you should convert on your own:
例如
>>> int(topsecret['Port']) 50022 >>> float(topsecret['CompressionLevel']) 9.0
常用方法method
打開配置文件
import configparser file = 'config.ini' # 創建配置文件對象 cfg = configparser.ConfigParser(comment_prefixes='#') # 讀取配置文件 cfg.read(file, encoding='utf-8')
這里只打開不做什么讀取和改變
讀取配置文件的所有section
file處替換為對應的配置文件即可
import configparser file = 'config.ini' cfg = configparser.ConfigParser(comment_prefixes='#') cfg.read(file, encoding='utf-8') # 獲取所有section sections = cfg.sections() # 顯示讀取的section結果 print(sections)
判斷有沒有對應的section!!!
當沒有對應的section就直接操作時程序會非正常結束
import configparser file = 'config.ini' cfg = configparser.ConfigParser(comment_prefixes='#') cfg.read(file, encoding='utf-8') if cfg.has_section("Default"): # 有沒有"Default" section print("存在Defaul section") else: print("不存在Defaul section")
判斷section下對應的Option
import configparser file = 'config.ini' cfg = configparser.ConfigParser(comment_prefixes='#') cfg.read(file, encoding='utf-8') # 檢測Default section下有沒有"CompressionLevel" option if cfg.cfg.has_option('Default', 'CompressionLevel'): print("存在CompressionLevel option") else: print("不存在CompressionLevel option")
添加section和option
最最重要的事情: 最后一定要寫入文件保存?。?!不然程序修改的結果不會修改到文件里
option在修改時不存在該option就會創建該option
import configparser file = 'config.ini' cfg = configparser.ConfigParser(comment_prefixes='#') cfg.read(file, encoding='utf-8') if not cfg.has_section("Color"): # 不存在Color section就創建 cfg.add_section('Color') # 設置sectin下的option的value,如果section不存在就會報錯 cfg.set('Color', 'isset', 'true') cfg.set('Color', 'version', '1.1.0') cfg.set('Color', 'orange', '150,100,100') # 把所作的修改寫入配置文件 with open(file, 'w', encoding='utf-8') as configfile: cfg.write(configfile)
刪除option
import configparser file = 'config.ini' cfg = configparser.ConfigParser(comment_prefixes='#') cfg.read(file, encoding='utf-8') cfg.remove_option('Default', 'CompressionLevel' # 把所作的修改寫入配置文件 with open(file, 'w', encoding='utf-8') as configfile: cfg.write(configfile)
刪除section
刪除section的時候會遞歸自動刪除該section下面的所有option,慎重使用
import configparser file = 'config.ini' cfg = configparser.ConfigParser(comment_prefixes='#') cfg.read(file, encoding='utf-8') cfg.remove_section('Default') # 把所作的修改寫入配置文件 with open(file, 'w', encoding='utf-8') as configfile: cfg.write(configfile)
實例
創建一個配置文件
import configparser file = 'config.ini' # 創建配置文件對象 cfg = configparser.ConfigParser(comment_prefixes='#') # 讀取配置文件 cfg.read(file, encoding='utf-8')``` # 實例 ## 創建一個配置文件 下面的demo介紹了如何檢測添加section和設置value ```python #!/usr/bin/env python # -*- encoding: utf-8 -*- ''' @File : file.py @Desc : 使用configparser讀寫配置文件demo @Author : Kearney @Contact : 191615342@qq.com @Version : 0.0.0 @License : GPL-3.0 @Time : 2020/10/20 10:23:52 ''' import configparser file = 'config.ini' # 創建配置文件對象 cfg = configparser.ConfigParser(comment_prefixes='#') # 讀取配置文件 cfg.read(file, encoding='utf-8') if not cfg.has_section("Default"): # 有沒有"Default" section cfg.add_section("Default") # 沒有就創建 # 設置"Default" section下的option的value # 如果這個section不存在就會報錯,所以上面要檢測和創建 cfg.set('Default', 'ServerAliveInterval', '45') cfg.set('Default', 'Compression', 'yes') cfg.set('Default', 'CompressionLevel', '9') cfg.set('Default', 'ForwardX11', 'yes') if not cfg.has_section("Color"): # 不存在Color就創建 cfg.add_section('Color') # 設置sectin下的option的value,如果section不存在就會報錯 cfg.set('Color', 'isset', 'true') cfg.set('Color', 'version', '1.1.0') cfg.set('Color', 'orange', '150,100,100') cfg.set('Color', 'lightgreen', '0,220,0') if not cfg.has_section("User"): cfg.add_section('User') cfg.set('User', 'iscrypted', 'false') cfg.set('User', 'Kearney', '191615342@qq.com') cfg.set('User', 'Tony', 'backmountain@gmail.com') # 把所作的修改寫入配置文件,并不是完全覆蓋文件 with open(file, 'w', encoding='utf-8') as configfile: cfg.write(configfile)
跑上面的程序就會創建一個config.ini的配置文件,然后添加section和option-value
文件內容如下所示
[Default] serveraliveinterval = 45 compression = yes compressionlevel = 9 forwardx11 = yes [Color] isset = true version = 1.1.0 orange = 150,100,100 lightgreen = 0,220,0 [User] iscrypted = false kearney = 191615342@qq.com tony = backmountain@gmail.com
關于Python使用configparser方法如何實現對配置文件進行讀寫問題的解答就分享到這里了,希望以上內容可以對大家有一定的幫助,如果你還有很多疑惑沒有解開,可以關注億速云行業資訊頻道了解更多相關知識。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。