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

您的位置:首頁技術(shù)文章
文章詳情頁

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

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

簡介

想寫一個登錄注冊的demo,但是以前的demo數(shù)據(jù)都寫在程序里面,每一關(guān)掉程序數(shù)據(jù)就沒保存住。。于是想著寫到配置文件里好了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.

配置文件的數(shù)據(jù)格式

下面的config.ini展示了配置文件的數(shù)據(jù)格式,用中括號[]括起來的為一個section例如Default、Color;每一個section有多個option,例如serveraliveinterval、compression等。option就是我們用來保存自己數(shù)據(jù)的地方,類似于鍵值對 optionname = value 或者是optionname : value (也可以設(shè)置允許空值)

[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

數(shù)據(jù)類型

在py configparser保存的數(shù)據(jù)中,value的值都保存為字符串類型,需要自己轉(zhuǎn)換為自己需要的數(shù)據(jù)類型

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’# 創(chuàng)建配置文件對象cfg = configparser.ConfigParser(comment_prefixes=’#’)# 讀取配置文件cfg.read(file, encoding=’utf-8’)

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

讀取配置文件的所有section

file處替換為對應(yīng)的配置文件即可

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

判斷有沒有對應(yīng)的section!!!

當沒有對應(yīng)的section就直接操作時程序會非正常結(jié)束

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下對應(yīng)的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

最最重要的事情: 最后一定要寫入文件保存?。。〔蝗怀绦蛐薷牡慕Y(jié)果不會修改到文件里

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

option在修改時不存在該option就會創(chuàng)建該option

import configparserfile = ’config.ini’cfg = configparser.ConfigParser(comment_prefixes=’#’)cfg.read(file, encoding=’utf-8’)if not cfg.has_section('Color'): # 不存在Color section就創(chuàng)建 cfg.add_section(’Color’)# 設(shè)置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)

實例

創(chuàng)建一個配置文件

import configparserfile = ’config.ini’# 創(chuàng)建配置文件對象cfg = configparser.ConfigParser(comment_prefixes=’#’)# 讀取配置文件cfg.read(file, encoding=’utf-8’)```# 實例## 創(chuàng)建一個配置文件下面的demo介紹了如何檢測添加section和設(shè)置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’# 創(chuàng)建配置文件對象cfg = configparser.ConfigParser(comment_prefixes=’#’)# 讀取配置文件cfg.read(file, encoding=’utf-8’)if not cfg.has_section('Default'): # 有沒有'Default' section cfg.add_section('Default') # 沒有就創(chuàng)建# 設(shè)置'Default' section下的option的value# 如果這個section不存在就會報錯,所以上面要檢測和創(chuàng)建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就創(chuàng)建 cfg.add_section(’Color’)# 設(shè)置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)

跑上面的程序就會創(chuàng)建一個config.ini的配置文件,然后添加section和option-value文件內(nèi)容如下所示

[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不規(guī)范,注釋和上一篇參考沖突

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

標簽: Python 編程
相關(guān)文章:
日本不卡不码高清免费观看,久久国产精品久久w女人spa,黄色aa久久,三上悠亚国产精品一区二区三区
国产精品激情电影| 久久91视频| 老司机免费视频一区二区三区| 日韩精品欧美激情一区二区| 久久精品国产精品亚洲毛片| 国内一区二区三区| 视频一区二区三区在线| 国产精品18| 99久久精品费精品国产| 999精品色在线播放| 91亚洲国产成人久久精品| 成人日韩在线观看| 水蜜桃久久夜色精品一区| 日本欧美不卡| 欧美黑人巨大videos精品| 日韩精品社区| 亚洲精品在线国产| 麻豆精品在线播放| 日韩精品免费观看视频| 亚洲精品极品| 久久九九电影| 在线日韩欧美| 久久精品免费一区二区三区| 日韩av在线播放网址| 久久麻豆精品| 伊人精品视频| 日韩精选在线| 亚洲精品系列| 亚洲精品2区| 欧美在线看片| 98精品视频| 一本一道久久a久久精品蜜桃| 日韩大片在线播放| japanese国产精品| 国产精品亚洲片在线播放| 久久精品国产99久久| 亚洲一区欧美二区| 国产精品嫩草99av在线| 欧美日韩第一| 青青伊人久久| 亚洲四虎影院| 久久99性xxx老妇胖精品| 精品亚洲二区| 国产精久久久| 成人精品久久| 日韩精品第一区| 国产欧美日韩一级| 九九精品调教| 欧美一级二区| 日韩欧美看国产| 日本成人手机在线| 99久久精品费精品国产| 国产精品激情电影| 亚洲欧美日韩专区| 欧美69视频| 日韩激情视频网站| 日韩精品国产精品| 午夜欧美精品| 国产主播一区| 欧美一区91| 国产精品一区亚洲| 视频一区欧美精品| 久久99蜜桃| 999久久久国产精品| 先锋亚洲精品| 91精品国产调教在线观看| 欧美在线日韩| 日本va欧美va瓶| 国产精品极品在线观看| 91精品美女| 亚洲精品免费观看| 国产日本精品| 国产精品a级| 日韩毛片视频| 狠狠干成人综合网| 久久男人av资源站| 欧美日韩在线播放视频| 久久国产精品免费一区二区三区| 欧美久久精品| 午夜影院欧美| 日韩av在线免费观看不卡| 国产成年精品| 麻豆网站免费在线观看| 久久先锋影音| 国产私拍福利精品视频二区| 精品久久91| 久久视频一区| 国产免费成人| 日韩视频在线一区二区三区| 日韩午夜电影| 国产成人调教视频在线观看| 色婷婷精品视频| 日本国产一区| 欧美精品99| 福利在线免费视频| 99热精品久久| 欧美有码在线| 国产精品videossex| 精品国产aⅴ| 色爱av综合网| 国产精品自拍区| 久久天堂影院| 国产精品一区二区三区美女 | 精品国产三区在线| 国产精品高颜值在线观看| 麻豆一区二区在线| 97精品在线| 日本不卡高清视频| 国产videos久久| 黄页网站一区| 精品黄色一级片| 久久亚洲国产精品一区二区| 国产精品扒开腿做爽爽爽软件| 久久久男人天堂| 免费久久精品视频| 亚洲一区二区三区四区五区午夜 | 精品久久不卡| 日韩在线短视频| 蜜桃久久久久久久| 日韩毛片视频| 黄色网一区二区| 综合激情网站| 欧美 日韩 国产一区二区在线视频 | 国产美女撒尿一区二区| 国产日韩欧美三区| 国产精品久久久久蜜臀| 欧美三区四区| 一区二区高清| 日本精品久久| 精品日产乱码久久久久久仙踪林| 国产v日韩v欧美v| 久久中文字幕二区| 日韩欧美网址| 欧美日本一区| 免费视频久久| 激情偷拍久久| 精品国产免费人成网站| 欧美+日本+国产+在线a∨观看| 尤物在线精品| 国产精品videossex久久发布| 欧美一区=区| 欧美天堂一区二区| 亚洲五月综合| 亚洲国产一区二区三区在线播放| 视频在线观看一区| 亚洲欧美专区| 亚洲黄色网址| 婷婷综合六月| 国产精品一区二区精品| 成人免费电影网址| 亚洲一区资源| 久久影视三级福利片| 久久国产99| 91p九色成人| 美女精品视频在线| 国产精品久久久久久久免费观看| 免费一级欧美在线观看视频| 亚洲少妇诱惑| 99久久夜色精品国产亚洲狼 | 另类av一区二区| 中文字幕成人| 蜜桃av.网站在线观看| 亚洲黄色在线| 婷婷成人av| 精品国产午夜肉伦伦影院| 国产精品最新| 国产精品对白久久久久粗| 精品精品久久| 久久久国产精品网站| 国产一区二区三区四区大秀| 麻豆国产精品一区二区三区| 麻豆视频久久| 蜜臀久久久99精品久久久久久| 波多野结衣久久精品| 精品一区在线| 精品国产一区二区三区av片| 日韩在线一二三区| 99久久夜色精品国产亚洲1000部| 亚洲免费毛片| 精品中国亚洲| 免费不卡中文字幕在线| 国产日韩欧美| 日韩欧美少妇| 国产亚洲人成a在线v网站| 97人人精品| av不卡免费看| 国产精品久久久久久久久久久久久久久| 欧美激情日韩| 亚洲综合在线电影| 亚洲精品在线二区| 国产suv精品一区二区四区视频| 在线精品视频一区| 久久精品高清| 欧美激情日韩| 日本aⅴ精品一区二区三区 | 亚洲免费在线| 精品久久视频| 久久亚洲国产| 日韩av资源网| 国产精品videossex久久发布|