最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Python利用configparser對(duì)配置文件進(jìn)行讀寫(xiě)操作

 更新時(shí)間:2020年11月03日 11:15:22   作者:Kearney form An idea  
這篇文章主要介紹了詳解Python利用configparser對(duì)配置文件進(jìn)行讀寫(xiě)操作,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下

簡(jiǎn)介

想寫(xiě)一個(gè)登錄注冊(cè)的demo,但是以前的demo數(shù)據(jù)都寫(xiě)在程序里面,每一關(guān)掉程序數(shù)據(jù)就沒(méi)保存住。。
于是想著寫(xiě)到配置文件里好了
Python自身提供了一個(gè)Module - configparser,來(lái)進(jìn)行對(duì)配置文件的讀寫(xiě)

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中把字母全變成了小寫(xiě)。本文以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ù)格式,用中括號(hào)[]括起來(lái)的為一個(gè)section例如Default、Color;每一個(gè)section有多個(gè)option,例如serveraliveinterval、compression等。
option就是我們用來(lái)保存自己數(shù)據(jù)的地方,類似于鍵值對(duì) optionname = value 或者是optionname : value (也可以設(shè)置允許空值)

[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

數(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

打開(kāi)配置文件

import configparser

file = 'config.ini'

# 創(chuàng)建配置文件對(duì)象
cfg = configparser.ConfigParser(comment_prefixes='#')
# 讀取配置文件
cfg.read(file, encoding='utf-8')

這里只打開(kāi)不做什么讀取和改變

讀取配置文件的所有section

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

import configparser

file = 'config.ini'
cfg = configparser.ConfigParser(comment_prefixes='#')
cfg.read(file, encoding='utf-8')

# 獲取所有section
sections = cfg.sections()
# 顯示讀取的section結(jié)果
print(sections)

判斷有沒(méi)有對(duì)應(yīng)的section!!!

當(dāng)沒(méi)有對(duì)應(yīng)的section就直接操作時(shí)程序會(huì)非正常結(jié)束

import configparser

file = 'config.ini'
cfg = configparser.ConfigParser(comment_prefixes='#')
cfg.read(file, encoding='utf-8')
if cfg.has_section("Default"): # 有沒(méi)有"Default" section
 print("存在Defaul section")
else:
	print("不存在Defaul section")	

判斷section下對(duì)應(yīng)的Option

import configparser

file = 'config.ini'
cfg = configparser.ConfigParser(comment_prefixes='#')
cfg.read(file, encoding='utf-8')
# 檢測(cè)Default section下有沒(méi)有"CompressionLevel" option
if cfg.cfg.has_option('Default', 'CompressionLevel'): 
 print("存在CompressionLevel option")
else:
	print("不存在CompressionLevel option")	 

添加section和option

最最重要的事情: 最后一定要寫(xiě)入文件保存?。?!不然程序修改的結(jié)果不會(huì)修改到文件里

  • 添加section前要檢測(cè)是否存在,否則存在重名的話就會(huì)報(bào)錯(cuò)程序非正常結(jié)束
  • 添加option前要確定section存在,否則同1

option在修改時(shí)不存在該option就會(huì)創(chuàng)建該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就創(chuàng)建
 cfg.add_section('Color')

# 設(shè)置sectin下的option的value,如果section不存在就會(huì)報(bào)錯(cuò)
cfg.set('Color', 'isset', 'true')
cfg.set('Color', 'version', '1.1.0') 
cfg.set('Color', 'orange', '150,100,100')

# 把所作的修改寫(xiě)入配置文件
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'

# 把所作的修改寫(xiě)入配置文件
with open(file, 'w', encoding='utf-8') as configfile:
 cfg.write(configfile)

刪除section

刪除section的時(shí)候會(huì)遞歸自動(dòng)刪除該section下面的所有option,慎重使用

import configparser

file = 'config.ini'
cfg = configparser.ConfigParser(comment_prefixes='#')
cfg.read(file, encoding='utf-8')

cfg.remove_section('Default')

# 把所作的修改寫(xiě)入配置文件
with open(file, 'w', encoding='utf-8') as configfile:
 cfg.write(configfile)

實(shí)例

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

import configparser

file = 'config.ini'

# 創(chuàng)建配置文件對(duì)象
cfg = configparser.ConfigParser(comment_prefixes='#')
# 讀取配置文件
cfg.read(file, encoding='utf-8')```

# 實(shí)例
## 創(chuàng)建一個(gè)配置文件
下面的demo介紹了如何檢測(cè)添加section和設(shè)置value
```python
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : file.py
@Desc : 使用configparser讀寫(xiě)配置文件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'

# 創(chuàng)建配置文件對(duì)象
cfg = configparser.ConfigParser(comment_prefixes='#')
# 讀取配置文件
cfg.read(file, encoding='utf-8')

if not cfg.has_section("Default"): # 有沒(méi)有"Default" section
 cfg.add_section("Default") # 沒(méi)有就創(chuàng)建

# 設(shè)置"Default" section下的option的value
# 如果這個(gè)section不存在就會(huì)報(bào)錯(cuò),所以上面要檢測(cè)和創(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不存在就會(huì)報(bào)錯(cuò)
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')

# 把所作的修改寫(xiě)入配置文件,并不是完全覆蓋文件
with open(file, 'w', encoding='utf-8') as configfile:
 cfg.write(configfile)

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

[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

References

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

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

相關(guān)文章

  • Tensorflow 實(shí)現(xiàn)線性回歸模型的示例代碼

    Tensorflow 實(shí)現(xiàn)線性回歸模型的示例代碼

    這篇文章主要介紹了Tensorflow 實(shí)現(xiàn)線性回歸模型,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2022-05-05
  • Python OpenCV讀取視頻報(bào)錯(cuò)的問(wèn)題解決

    Python OpenCV讀取視頻報(bào)錯(cuò)的問(wèn)題解決

    大家好,本篇文章主要講的是Python OpenCV讀取視頻報(bào)錯(cuò)的問(wèn)題解決,感興趣的同學(xué)趕快來(lái)看一看吧,對(duì)你有幫助的話記得收藏一下
    2022-01-01
  • Python Pytorch深度學(xué)習(xí)之核心小結(jié)

    Python Pytorch深度學(xué)習(xí)之核心小結(jié)

    今天小編就為大家分享一篇關(guān)于Pytorch核心小結(jié)的文章,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2021-10-10
  • Jupyter安裝拓展nbextensions及解決官網(wǎng)下載慢的問(wèn)題

    Jupyter安裝拓展nbextensions及解決官網(wǎng)下載慢的問(wèn)題

    這篇文章主要介紹了Jupyter安裝拓展nbextensions及解決官網(wǎng)下載慢的問(wèn)題,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03
  • Python使用gmplot創(chuàng)建動(dòng)態(tài)地圖可視化

    Python使用gmplot創(chuàng)建動(dòng)態(tài)地圖可視化

    gmplot 是一個(gè) Python 庫(kù),用于基于 Google Maps 的靜態(tài)地圖生成可視化,它提供簡(jiǎn)單的 API 來(lái)繪制標(biāo)記、路徑、熱力圖等地理信息數(shù)據(jù),本文給大家介紹了如何使用 gmplot 在 Python 中創(chuàng)建動(dòng)態(tài)地圖可視化,需要的朋友可以參考下
    2024-12-12
  • 在Python中使用turtle繪制多個(gè)同心圓示例

    在Python中使用turtle繪制多個(gè)同心圓示例

    今天小編就為大家分享一篇在Python中使用turtle繪制多個(gè)同心圓示例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧
    2019-11-11
  • Python深度學(xué)習(xí)pytorch卷積神經(jīng)網(wǎng)絡(luò)LeNet

    Python深度學(xué)習(xí)pytorch卷積神經(jīng)網(wǎng)絡(luò)LeNet

    這篇文章主要為大家講解了Python深度學(xué)習(xí)中的pytorch卷積神經(jīng)網(wǎng)絡(luò)LeNet的示例解析,有需要的朋友可以借鑒參考下希望能夠有所幫助
    2021-10-10
  • Python標(biāo)準(zhǔn)庫(kù)sys庫(kù)常用功能詳解

    Python標(biāo)準(zhǔn)庫(kù)sys庫(kù)常用功能詳解

    這篇文章主要介紹了Python標(biāo)準(zhǔn)庫(kù)sys庫(kù)常用功能詳解,sys是Python提供的程序與解釋器交互的標(biāo)準(zhǔn)庫(kù),文章圍繞主題展開(kāi)相關(guān)介紹,需要的朋友可以參考一下
    2022-07-07
  • Flask框架學(xué)習(xí)筆記(一)安裝篇(windows安裝與centos安裝)

    Flask框架學(xué)習(xí)筆記(一)安裝篇(windows安裝與centos安裝)

    Flask是一個(gè)輕量級(jí)的Web應(yīng)用框架, 使用Python編寫(xiě)。Flask也被稱為 “microframework” ,因?yàn)樗褂煤?jiǎn)單的核心,用 extension 增加其他功能。
    2014-06-06
  • Python的語(yǔ)法基礎(chǔ)你真的了解嗎

    Python的語(yǔ)法基礎(chǔ)你真的了解嗎

    這篇文章主要為大家詳細(xì)介紹了Python的語(yǔ)法基礎(chǔ),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助
    2022-02-02

最新評(píng)論

垫江县| 霍山县| 余庆县| 昆明市| 肃南| 高阳县| 海兴县| 曲阜市| 尚义县| 肥东县| 陇南市| 安达市| 攀枝花市| 开封县| 新源县| 昌乐县| 枣强县| 南投市| 霍林郭勒市| 文水县| 房产| 睢宁县| 曲沃县| 嘉义县| 思南县| 信丰县| 泽州县| 息烽县| 东至县| 淮南市| 尉犁县| 贡觉县| 吴旗县| 水城县| 虹口区| 双城市| 右玉县| 资兴市| 襄城县| 克什克腾旗| 兰溪市|