日本不卡不码高清免费观看,久久国产精品久久w女人spa,黄色aa久久,三上悠亚国产精品一区二区三区

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

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

瀏覽:106日期: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 編程
相關文章:
日本不卡不码高清免费观看,久久国产精品久久w女人spa,黄色aa久久,三上悠亚国产精品一区二区三区
欧美国产日本| 欧美国产视频| 日韩免费福利视频| 秋霞影院一区二区三区| 日韩欧美一区二区三区免费看| 国产伦久视频在线观看| 色婷婷久久久| 三级欧美在线一区| 日本亚洲最大的色成网站www | 国产精品videossex| 欧美激情aⅴ一区二区三区 | 99亚洲视频| 亚洲日韩中文字幕一区| 国产欧美69| 国产一区2区在线观看| 成人啊v在线| 丝袜脚交一区二区| 亚洲色图国产| 欧美国产亚洲精品| 久久国产日本精品| 中文字幕视频精品一区二区三区| 日本不卡高清视频| 久久影院资源站| 欧美丝袜一区| 亚洲狼人精品一区二区三区| 青青草国产精品亚洲专区无| 精品一区二区三区在线观看视频| 麻豆视频在线观看免费网站黄 | 午夜精品福利影院| 精品资源在线| 婷婷激情综合| 欧美日一区二区三区在线观看国产免| 精品国产精品国产偷麻豆| 久久免费大视频| 日本成人中文字幕| 欧美少妇精品| 久久国产日韩欧美精品| 日韩成人亚洲| 日韩福利视频导航| 久久精品电影| 国产精品一区二区中文字幕| 国产99精品| 国产精品久av福利在线观看| 国内精品福利| 国产精品白丝久久av网站| 成人一区不卡| 欧美永久精品| 国产精品99一区二区| 国产精品主播| 亚洲一区二区免费看| 成人在线超碰| 欧美视频精品全部免费观看| 免费国产自久久久久三四区久久| 国产日韩一区| 天堂va蜜桃一区二区三区| 国产在线看片免费视频在线观看| 日韩精品久久理论片| 影视先锋久久| 丰满少妇一区| 久久国际精品| 午夜精品影视国产一区在线麻豆| 成人国产精品一区二区免费麻豆| 亚洲人成在线影院| 女主播福利一区| 精品日韩一区| 国产九九精品| 四虎精品永久免费| 香蕉久久国产| 欧美日韩国产一区二区三区不卡| 美女视频免费精品| 日韩高清二区| 蜜桃视频在线观看一区| 久久高清免费| 中文在线免费视频| 老司机精品视频在线播放| 青草国产精品久久久久久| 久久精品亚洲人成影院| 国产成人精品一区二区三区视频| 久久国际精品| 国产日韩欧美| 国产精品入口久久| 国产欧美日韩精品一区二区三区| 亚洲精品乱码| 亚洲制服一区| 免费国产亚洲视频| 日韩制服丝袜先锋影音| 国产二区精品| 亚洲少妇一区| 欧美日韩日本国产亚洲在线 | 奇米狠狠一区二区三区| 亚洲资源av| 夜夜嗨av一区二区三区网站四季av| 欧美日韩一区二区三区视频播放| 中文字幕在线视频网站| 国产精品久久久久久久久久10秀| 精品国产美女a久久9999| 久久这里只有精品一区二区| 久久精品国产精品亚洲毛片| 久久精品一区二区国产| 精品99久久| 色一区二区三区四区| yellow在线观看网址| 日韩精品第一区| 亚洲成人va| 日韩精品永久网址| 美女久久久久| 日韩一区精品字幕| 亚洲精品欧美| 国产调教精品| 欧美aa在线视频| 国语精品一区| 九九精品调教| 国产精品三上| 日韩精品一级| 精品久久影院| 99精品在线免费在线观看| 国产精品7m凸凹视频分类| 久久成人国产| 国产精品三级| 国产三级精品三级在线观看国产| 精品理论电影在线| 国产一区久久| 日本aⅴ亚洲精品中文乱码| 里番精品3d一二三区| 桃色一区二区| 亚洲丝袜啪啪| 蜜桃久久久久| 91精品国产调教在线观看| 日韩午夜免费| 欧美日韩一视频区二区| 高清不卡一区| av不卡在线| 国产精品欧美在线观看| 欧美成人精品三级网站| 天堂日韩电影| 亚洲美女91| av免费不卡国产观看| 在线视频精品| 久久精品亚洲| 久久国产精品99国产| 久久99性xxx老妇胖精品| 久久在线免费| 久久国产人妖系列| 宅男在线一区| 国产麻豆一区二区三区| 国产一在线精品一区在线观看| 日韩美女国产精品| 国产成人精品亚洲日本在线观看| 蜜桃伊人久久| 日韩精品第一| 日本精品影院| 国产乱码精品一区二区亚洲| 在线日韩欧美| 国产精品激情电影| 玖玖玖国产精品| 在线亚洲人成| 欧美精品影院| 黄色成人精品网站| 国产精品igao视频网网址不卡日韩 | 激情视频网站在线播放色| 欧美午夜精彩| 国产日韩欧美一区二区三区| 亚洲国产成人二区| 日韩中文字幕无砖| 久久人人88| 另类欧美日韩国产在线| 蜜臀a∨国产成人精品| 亚洲国产成人二区| 欧美私人啪啪vps| 国产女优一区| 精品日韩视频| 久久精品国产精品亚洲毛片| 久久久蜜桃一区二区人| 国产精品一区二区av日韩在线| 91九色精品| 桃色av一区二区| 国产伦乱精品| 首页国产欧美久久| 久久久夜夜夜| 在线看片国产福利你懂的| 日韩毛片一区| 日韩午夜黄色| 日韩精品免费一区二区在线观看| 久久99影视| 久久国产婷婷国产香蕉| 另类亚洲自拍| 五月天综合网站| 国产精品免费精品自在线观看| 亚洲少妇诱惑| 理论片午夜视频在线观看| 久久国产麻豆精品| 在线观看亚洲精品福利片| 亚洲成人三区| 亚洲国产影院| 久久国产亚洲精品| 91精品国产成人观看| 亚洲国产成人二区| sm捆绑调教国产免费网站在线观看| 国产精品xxxav免费视频| 日韩精品成人|