电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

詳解Python利用configparser對配置文件進行讀寫操作

瀏覽:42日期:2022-07-06 14:32:15

簡介

想寫一個登錄注冊的demo,但是以前的demo數據都寫在程序里面,每一關掉程序數據就沒保存住。。于是想著寫到配置文件里好了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 inthe 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 = 45compression = yescompressionlevel = 9forwardx11 = yesvalues like this: 1000000or this: 3.14159265359[No Values]key_without_valueempty string value here =[Color]isset = trueversion = 1.1.0orange = 150,100,100lightgreen = 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 configparserfile = ’config.ini’# 創建配置文件對象cfg = configparser.ConfigParser(comment_prefixes=’#’)# 讀取配置文件cfg.read(file, encoding=’utf-8’)

這里只打開不做什么讀取和改變

讀取配置文件的所有section

file處替換為對應的配置文件即可

import configparserfile = ’config.ini’cfg = configparser.ConfigParser(comment_prefixes=’#’)cfg.read(file, encoding=’utf-8’)# 獲取所有sectionsections = cfg.sections()# 顯示讀取的section結果print(sections)

判斷有沒有對應的section!!!

當沒有對應的section就直接操作時程序會非正常結束

import configparserfile = ’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 configparserfile = ’config.ini’cfg = configparser.ConfigParser(comment_prefixes=’#’)cfg.read(file, encoding=’utf-8’)# 檢測Default section下有沒有'CompressionLevel' optionif cfg.cfg.has_option(’Default’, ’CompressionLevel’): print('存在CompressionLevel option')else:print('不存在CompressionLevel option')

添加section和option

最最重要的事情: 最后一定要寫入文件保存!!!不然程序修改的結果不會修改到文件里

添加section前要檢測是否存在,否則存在重名的話就會報錯程序非正常結束 添加option前要確定section存在,否則同1

option在修改時不存在該option就會創建該option

import configparserfile = ’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 configparserfile = ’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 configparserfile = ’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 configparserfile = ’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 configparserfile = ’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 = 45compression = yescompressionlevel = 9forwardx11 = yes[Color]isset = trueversion = 1.1.0orange = 150,100,100lightgreen = 0,220,0[User]iscrypted = falsekearney = 191615342@qq.comtony = backmountain@gmail.com

References

Configuration file parser - py2Configuration file parser - py3python讀取配置文件(ini、yaml、xml)-ini只讀不寫。。python 編寫配置文件 - open不規范,注釋和上一篇參考沖突

到此這篇關于詳解Python利用configparser對配置文件進行讀寫操作的文章就介紹到這了,更多相關Python configparser配置文件讀寫內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 天然气分析仪-液化气二甲醚分析仪|传昊仪器 | 工控机,嵌入式主板,工业主板,arm主板,图像采集卡,poe网卡,朗锐智科 | 一体化隔油提升设备-餐饮油水分离器-餐厨垃圾处理设备-隔油池-盐城金球环保产业发展有限公司 | 耐火浇注料-喷涂料-浇注料生产厂家_郑州市元领耐火材料有限公司 耐力板-PC阳光板-PC板-PC耐力板 - 嘉兴赢创实业有限公司 | 暴风影音| 电机修理_二手电机专家-河北豫通机电设备有限公司(原石家庄冀华高压电机维修中心) | 青岛成人高考_山东成考报名网| 气象监测系统_气象传感器_微型气象仪_气象环境监测仪-山东风途物联网 | 电缆隧道在线监测-智慧配电站房-升压站在线监测-江苏久创电气科技有限公司 | 宁波普瑞思邻苯二甲酸盐检测仪,ROHS2.0检测设备,ROHS2.0测试仪厂家 | 派克防爆伺服电机品牌|国产防爆伺服电机|高低温伺服电机|杭州摩森机电科技有限公司 | 线材成型机,线材折弯机,线材成型机厂家,贝朗自动化设备有限公司1 | 定量包装机,颗粒定量包装机,粉剂定量包装机,背封颗粒包装机,定量灌装机-上海铸衡电子科技有限公司 | 上海电子秤厂家,电子秤厂家价格,上海吊秤厂家,吊秤供应价格-上海佳宜电子科技有限公司 | LINK FASHION 童装·青少年装展 河南卓美创业科技有限公司-河南卓美防雷公司-防雷接地-防雷工程-重庆避雷针-避雷器-防雷检测-避雷带-避雷针-避雷塔、机房防雷、古建筑防雷等-山西防雷公司 | 铜镍-康铜-锰铜-电阻合金-NC003 - 杭州兴宇合金有限公司 | 北京征地律师,征地拆迁律师,专业拆迁律师,北京拆迁律师,征地纠纷律师,征地诉讼律师,征地拆迁补偿,拆迁律师 - 北京凯诺律师事务所 | 一体化隔油提升设备-餐饮油水分离器-餐厨垃圾处理设备-隔油池-盐城金球环保产业发展有限公司 | 回转窑-水泥|石灰|冶金-巩义市瑞光金属制品有限责任公司 | 防伪溯源|防窜货|微信二维码营销|兆信_行业内领先的防伪防窜货数字化营销解决方案供应商 | 硫化罐_蒸汽硫化罐_大型硫化罐-山东鑫泰鑫智能装备有限公司 | 别墅图纸超市|别墅设计图纸|农村房屋设计图|农村自建房|别墅设计图纸及效果图大全 | 台式核磁共振仪,玻璃软化点测定仪,旋转高温粘度计,测温锥和测温块-上海麟文仪器 | 澳门精准正版免费大全,2025新澳门全年免费,新澳天天开奖免费资料大全最新,新澳2025今晚开奖资料,新澳马今天最快最新图库-首页-东莞市傲马网络科技有限公司 | 莱州网络公司|莱州网站建设|莱州网站优化|莱州阿里巴巴-莱州唯佳网络科技有限公司 | 深圳美安可自动化设备有限公司,喷码机,定制喷码机,二维码喷码机,深圳喷码机,纸箱喷码机,东莞喷码机 UV喷码机,日期喷码机,鸡蛋喷码机,管芯喷码机,管内壁喷码机,喷码机厂家 | 蔬菜配送公司|蔬菜配送中心|食材配送|饭堂配送|食堂配送-首宏公司 | 点胶机_点胶阀_自动点胶机_智能点胶机_喷胶机_点胶机厂家【欧力克斯】 | 跨境物流_美国卡派_中大件运输_尾程派送_海外仓一件代发 - 广州环至美供应链平台 | 上海公众号开发-公众号代运营公司-做公众号的公司企业服务商-咏熠软件 | 中图网(原中国图书网):网上书店,尾货特色书店,30万种特价书低至2折! | EPK超声波测厚仪,德国EPK测厚仪维修-上海树信仪器仪表有限公司 | 乐之康护 - 专业护工服务平台,提供医院陪护-居家照护-居家康复 | 哈尔滨治「失眠/抑郁/焦虑症/精神心理」专科医院排行榜-京科脑康免费咨询 一对一诊疗 | 干法制粒机_智能干法制粒机_张家港市开创机械制造有限公司 | 合肥防火门窗/隔断_合肥防火卷帘门厂家_安徽耐火窗_良万消防设备有限公司 | 北京三友信电子科技有限公司-ETC高速自动栏杆机|ETC机柜|激光车辆轮廓测量仪|嵌入式车道控制器 | 电渗析,废酸回收,双极膜-山东天维膜技术有限公司 | 土壤养分检测仪_肥料养分检测仪_土壤水分检测仪-山东莱恩德仪器 大型多片锯,圆木多片锯,方木多片锯,板材多片锯-祥富机械有限公司 | 管理会计网-PCMA初级管理会计,中级管理会计考试网站 | 广东恩亿梯电源有限公司【官网】_UPS不间断电源|EPS应急电源|模块化机房|电动汽车充电桩_UPS电源厂家(恩亿梯UPS电源,UPS不间断电源,不间断电源UPS) |