Python中ini配置文件读写的实现

导入模块

import configparser # py3

写入

config = configparser.ConfigParser()

config["DEFAULT"] = {
    'ServerAliveInterval': '45',
    'Compression': 'yes',
    'CompressionLevel': '9'
    }

config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'

config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'  # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here

config['DEFAULT']['ForwardX11'] = 'yes'

# 写入文件
with open('example.ini', 'w') as configfile:
    config.write(configfile)

读取

config = configparser.ConfigParser()
config.read("example.ini")

print(config.defaults())
# OrderedDict([('compression', 'yes')])

print(config.sections())
# ['bitbucket.org', 'topsecret.server.com']

print(config['bitbucket.org']['User'])
# hg

print(config.options("topsecret.server.com"))
# ['port', 'compression']

print(config.items("topsecret.server.com"))
# [('compression', 'yes'), ('port', '50022')]

print(config.get("topsecret.server.com", "port"))
# 50022

修改

print(config.has_section("Name"))

# 删除
config.remove_section("Name")

# 添加
config.add_section("Name")
config["Name"]["name"] = "Tom"
config["Name"]["asname"] = "Jimi"

# 设置
config.remove_option("Name", "asname")
config.set("Name", "name", "Jack")

# 保存
config.write(open("example.ini", "w"))

附:ini文件

[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
host port = 50022
forwardx11 = no

help(configparser)

"""
CLASSES

    class ConfigParser(RawConfigParser)
     |  ConfigParser implementing interpolation.
     |  
     |  add_section(self, section)
     |      Create a new section in the configuration.  Extends
     |      RawConfigParser.add_section by validating if the section name is
     |      a string.
     |  
     |  set(self, section, option, value=None)
     |      Set an option.  Extends RawConfigParser.set by validating type and
     |      interpolation syntax on the value.
     |  
     |  defaults(self)
     |  
     |  get(self, section, option, *, raw=False, vars=None, fallback=<object object at 0x0000000002F42120>)
     |      Get an option value for a given section.
     |  
     |  getboolean(self, section, option, *, raw=False, vars=None, fallback=<object object at 0x0000000002F42120>)
     |  
     |  getfloat(self, section, option, *, raw=False, vars=None, fallback=<object object at 0x0000000002F42120>)
     |  
     |  getint(self, section, option, *, raw=False, vars=None, fallback=<object object at 0x0000000002F42120>)
     |  
     |  has_option(self, section, option)
     |      Check for the existence of a given option in a given section.
     |      If the specified `section' is None or an empty string, DEFAULT is
     |      assumed. If the specified `section' does not exist, returns False.
     |  
     |  has_section(self, section)
     |      Indicate whether the named section is present in the configuration.

     |  items(self, section=<object object at 0x0000000002F42120>, raw=False, vars=None)
     |      Return a list of (name, value) tuples for each option in a section.
     |  
     |  options(self, section)
     |      Return a list of option names for the given section name.
     |  popitem(self)
     |      Remove a section from the parser and return it as
     |  read(self, filenames, encoding=None)
     |      Read and parse a filename or a list of filenames.
     |      Return list of successfully read files.
     |  
     |  read_dict(self, dictionary, source='<dict>')
     |      Read configuration from a dictionary.
     |  
     |  read_file(self, f, source=None)
     |      Like read() but the argument must be a file-like object.
     |      
     |  read_string(self, string, source='<string>')
     |      Read configuration from a given string.
     |  
     |  readfp(self, fp, filename=None)
     |      Deprecated, use read_file instead.
     |  
     |  remove_option(self, section, option)
     |      Remove an option.
     |  
     |  remove_section(self, section)
     |      Remove a file section.
     |  
     |  sections(self)
     |      Return a list of section names, excluding [DEFAULT]
     |  
     |  write(self, fp, space_around_delimiters=True)
     |      Write an .ini-format representation of the configuration state.
     |  
     |  clear(self)
     |      D.clear() -> None.  Remove all items from D.
     |  
     |  pop(self, key, default=<object object at 0x0000000002F42040>)
     |      D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
     |      If key is not found, d is returned if given, otherwise KeyError is raised.
     |  
     |  setdefault(self, key, default=None)
     |      D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
     |  
     |  update(*args, **kwds)
     |      D.update([E, ]**F) -> None.  Update D from mapping/iterable E and F.
     |      If E present and has a .keys() method, does:     for k in E: D[k] = E[k]
     |      If E present and lacks .keys() method, does:     for (k, v) in E: D[k] = v
     |      In either case, this is followed by: for k, v in F.items(): D[k] = v
     |  
     |  keys(self)
     |      D.keys() -> a set-like object providing a view on D's keys
     |  
     |  values(self)
     |      D.values() -> an object providing a view on D's values
     |  
"""

到此这篇关于Python中ini配置文件读写的实现的文章就介绍到这了,更多相关Python ini文件读写内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • Python读取ini配置文件传参的简单示例

    前言 为了往我们写好的Python代码传入参数,有很多种方法,比如使用input获取从DOS 输入的参数,又或者读取txt 文件中的字符作为参数.但为了比较规范,在windows 上我们常常用ini的配置文件进行工具配置.因此,今天我们说明下如果使用python 读取ini 文件. 一.后缀 ini 配置文件介绍 我们新建一个txt 文件,将后缀改为.ini形式,在ini文件中按照分组写入需要的参数. ini示例: # 定义arnold分组 [arnold] # 分组名称 platformNam

  • python读取ini配置的类封装代码实例

    这篇文章主要介绍了python读取ini配置的类封装代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 此为基础封装,未考虑过多异常处理 类 # coding:utf-8 import configparser import os class IniCfg(): def __init__(self): self.conf = configparser.ConfigParser() self.cfgpath = '' def checkSec

  • Python操作配置文件ini的三种方法讲解

    python 操作配置文件ini的三种方法 方法一:crudini 命令 说明 crudini命令是Linux下的一个操作配置文件的命令工具 用法 crudini --set [--existing] config_file section [param] [value] # 修改配置文件内容 crudini --get [--format=sh|ini] config_file [section] [param] # 获取配置文件内容 crudini --del [--existing] co

  • Python3读写ini配置文件的示例

    ini文件即Initialization File初始化文件,在应用程序及框架中常作为配置文件使用,是一种静态纯文本文件,使用记事本即可编辑. 配置文件的主要功能就是存储一批变量和变量值,在ini文件中使用[章(Section)]对变量进行了分组,基本格式如下. # filename: config.ini [user] name=admin password=123456 is_admin=true [mysql] host=10.10.10.10 port=3306 db=apitest u

  • Python常用配置文件ini、json、yaml读写总结

    本文参考文章,出于学习目的,写本文. 开发项目时,为了维护一些经常需要变更的数据,比如数据库的连接信息.请求的url.测试数据等,需要将这些数据写入配置文件,将数据和代码分离,只需要修改配置文件的参数,就可以快速完成环境的切换或者测试数据的更新,常用的配置文件格式有ini.json.yaml等,下面简单给大家介绍下,Python如何读写这几种格式的文件. 1.ini格式 ini 即 Initialize ,是Windows中常用的配置文件格式,结构比较简单,主要由节(Section).键(key

  • Python实现读写INI配置文件的方法示例

    本文实例讲述了Python实现读写INI配置文件的方法.分享给大家供大家参考,具体如下: # -*- coding: utf-8 -*- import ConfigParser import os '''读写配置文件的类 [section] logpath = D:\log\ imageminsize = 200 ''' class ConfigFile: '''构造函数:初始化''' def __init__(self,fileName): fileName = unicode(fileNam

  • python操作ini类型配置文件的实例教程

    一.ini文件介绍 INI文件格式是某些平台或软件上的配置文件的非正式标准,以节(section)和键(key)构成,常用于微软Windows操作系统中.这种配置文件的文件扩展名多为INI 二.ini文件的结构 片段[section] 键名 option 值 value 三.实例: 实例1 python25.ini [teachers] name = ['yushen', 'pianpian'] age = 16 gender = '女' favor = {"movie": "

  • python读取ini配置文件过程示范

    这篇文章主要介绍了python读取ini配置文件过程示范,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 安装 pip install configparser 1 配置文件 config.ini: [MysqlDB] user=root passwd=123456 sport=3306 db_name=my_db charset=utf-8 获取参数: import configparser config = configparser.Conf

  • 基于Python3读写INI配置文件过程解析

    ini文件简介 ini是我们常见到的配置文件格式之一. ini是微软Windows操作系统中的文件扩展名(也常用在其他系统). INI是英文"初始化(Initial)"的缩写.正如该术语所表示的,INI文件被用来对操作系统或特定程序初始化或进行参数设置. 通过它,可以将经常需要改变的参数保存起来(而且还可读),使程序更加的灵活. 我先给出一个ini文件的示例. [School] ip = 10.15.40.123 mask = 255.255.255.0 gateway = 10.15

  • Python中ini配置文件读写的实现

    导入模块 import configparser # py3 写入 config = configparser.ConfigParser() config["DEFAULT"] = {     'ServerAliveInterval': '45',     'Compression': 'yes',     'CompressionLevel': '9'     } config['bitbucket.org'] = {} config['bitbucket.org']['User'

  • 基于python的ini配置文件操作工具类

    本文实例为大家分享了python的ini配置文件操作工具类的具体代码,供大家参考,具体内容如下 #!/usr/bin/env python # -*- coding: utf-8 -*- """ @Time : 2018/6/22 @Author : LiuXueWen @Site : @File : Util_Ini_Operation.py @Software: PyCharm @Description: ini配置文件操作工具类 1.读取.ini配置文件 2.修改.in

  • Python的ini配置文件你了解吗

    目录 INI介绍 关于configparser INI文件格式 读取配置文件 总结 INI介绍 INI是英文“初始化”(initialization)的缩写,被用来对操作系统或特定程序初始化或进行参数设置.由节(section). 键(key).值(value)构成.在windows系统中有很多INI文件,例如“System32.ini”和“Win.ini”,相信大家并不陌生.Python 中操作配置文件的模块为configparser,这个模块可以用来解析与Windows上INI文件结构类似的

  • 在python中使用pyspark读写Hive数据操作

    1.读Hive表数据 pyspark读取hive数据非常简单,因为它有专门的接口来读取,完全不需要像hbase那样,需要做很多配置,pyspark提供的操作hive的接口,使得程序可以直接使用SQL语句从hive里面查询需要的数据,代码如下: from pyspark.sql import HiveContext,SparkSession _SPARK_HOST = "spark://spark-master:7077" _APP_NAME = "test" spa

  • python中yaml配置文件模块的使用详解

    简述 和GNU一样,YAML是一个递归着说"不"的名字.不同的是,GNU对UNIX说不,YAML说不的对象是XML. YAML不是XML. 为什么不是XML呢?因为: YAML的可读性好. YAML和脚本语言的交互性好. YAML使用实现语言的数据类型. YAML有一个一致的信息模型. YAML易于实现. 上面5条也就是XML不足的地方.同时,YAML也有XML的下列优点: YAML可以基于流来处理: YAML表达能力强,扩展性好. 总之,YAML试图用一种比XML更敏捷的方式,来完成

  • 如何在python中处理配置文件代码实例

    配置文件是一种计算机文件,可以为一些计算机程序配置参数和初始设置,在内容形式上是一个一个键值对的记录. testcase.yaml文件: excel: filename: "testcase.xlsx" 将yaml库做二次封装: import yaml class HandleYaml: def __init__(self, filename=None): if filename is None: self.filename = 'testcase.yaml' else: self.f

  • Python ini配置文件示例详解

    目录 INI介绍 关于configparser INI文件格式 读取配置文件 写入配置文件 总结 INI介绍 INI是英文“初始化”(initialization)的缩写,被用来对操作系统或特定程序初始化或进行参数设置.由节(section). 键(key).值(value)构成.在windows系统中有很多INI文件,例如“System32.ini”和“Win.ini”,相信大家并不陌生.Python 中操作配置文件的模块为configparser,这个模块可以用来解析与Windows上INI

  • Python实现解析ini配置文件的示例详解

    目录 楔子 ini 文件 特殊格式 小结 楔子 在开发过程中,配置文件是少不了的,只不过我们有时会将 py 文件作为配置文件(config.py),然后在其它的模块中直接导入.这样做是一个好主意,不过配置文件是有专门的格式的,比如:ini, yaml, toml 等等. 而对于 Python 而言,也都有相应的库来解析相应格式的文件,下面我们来看看 ini 文件要如何解析. ini 文件 先来了解一下 ini 文件的格式: [satori] name = 古明地觉 age = 16 where 

随机推荐