I need to read, write and create an INI file with Python3.
我需要用Python3读、写和创建一个INI文件。
FILE.INI
FILE.INI
default_path = "/path/name/"default_file = "file.txt"
Python File:
Python文件:
# read file and if not existsini = iniFile( 'FILE.INI' )# Get and Print Config Line "default_path"getLine = ini.default_path# Print (string)/path/nameprint getLine# Append new line and if exists edit this lineini.append( 'default_path' , 'var/shared/' )ini.append( 'default_message' , 'Hey! help me!!' )
UPDATE FILE.INI
更新FILE.INI
default_path = "var/shared/"default_file = "file.txt"default_message = "Hey! help me!!"
5 个解决方案
#1
95
This can be something to start with:
这可以从以下几个方面开始:
import configparserconfig = configparser.ConfigParser()config.read('FILE.INI')print(config['DEFAULT']['path']) # -> "/path/name/"config['DEFAULT']['path'] = '/var/shared/' # updateconfig['DEFAULT']['default_message'] = 'Hey! help me!!' # createwith open('FILE.INI', 'w') as configfile: # save config.write(configfile)
You can find more at the official configparser documentation.
您可以在官方的configparser文档中找到更多信息。
#2
39
Here's a complete read, update and write example.
这里有一个完整的读、更新和写示例。
Input file, test.ini
输入文件,test.ini
[section_a]string_val = hellobool_val = falseint_val = 11pi_val = 3.14
Working code.
工作代码。
try: from configparser import ConfigParserexcept ImportError: from ConfigParser import ConfigParser # ver. < 3.0# instantiateconfig = ConfigParser()# parse existing fileconfig.read('test.ini')# read values from a sectionstring_val = config.get('section_a', 'string_val')bool_val = config.getboolean('section_a', 'bool_val')int_val = config.getint('section_a', 'int_val')float_val = config.getfloat('section_a', 'pi_val')# update existing valueconfig.set('section_a', 'string_val', 'world')# add a new section and some valuesconfig.add_section('section_b')config.set('section_b', 'meal_val', 'spam')config.set('section_b', 'not_found_val', 404)# save to a filewith open('test_update.ini', 'w') as configfile: config.write(configfile)
Output file, test_update.ini
输出文件,test_update.ini
[section_a]string_val = worldbool_val = falseint_val = 11pi_val = 3.14[section_b]meal_val = spamnot_found_val = 404
The original input file remains untouched.
原始输入文件保持原样。
#3
8
http://docs.python.org/library/configparser.html
http://docs.python.org/library/configparser.html
Python's standard library might be helpful in this case.
在这种情况下,Python的标准库可能会有帮助。
#4
2
The standard ConfigParser
normally requires access via config['section_name']['key']
, which is no fun. A little modification can deliver attribute access:
标准的ConfigParser通常要求通过config['section_name']['key']进行访问,这一点都不好玩。稍微修改一下就可以实现属性访问:
class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self
AttrDict
is a class derived from dict
which allows access via both dictionary keys and attribute access: that means a.x is a['x']
AttrDict是一个派生自dict类型的类,它允许通过字典键和属性访问:即a。x是一个[' x ']
We can use this class in ConfigParser
:
我们可以在ConfigParser中使用这个类:
config = configparser.ConfigParser(dict_type=AttrDict)config.read('application.ini')
and now we get application.ini
with:
现在我们有了应用。ini:
[general]key = value
as
作为
>>> config._sections.general.key'value'
#5
2
ConfigObj is a good alternative to ConfigParser which offers a lot more flexibility:
ConfigObj是ConfigParser的一个很好的替代选择,它提供了更多的灵活性:
- Nested sections (subsections), to any level
- 嵌套节(子节),任何级别
- List values
- 列表值
- Multiple line values
- 多个线值
- String interpolation (substitution)
- 字符串插值(替换)
- Integrated with a powerful validation system including automatic type checking/conversion repeated sections and allowing default values
- 集成了一个强大的验证系统,包括自动类型检查/转换重复部分和允许默认值
- When writing out config files, ConfigObj preserves all comments and the order of members and sections
- 在编写配置文件时,ConfigObj保留所有注释和成员和部分的顺序。
- Many useful methods and options for working with configuration files (like the 'reload' method)
- 使用配置文件的许多有用的方法和选项(比如“reload”方法)
- Full Unicode support
- 完整的Unicode支持
It has some draw backs:
它有一些不足之处:
- You cannot set the delimiter, it has to be
=
… (pull request) - 不能设置分隔符,它必须是=…(拉请求)
- You cannot have empty values, well you can but they look liked:
fuabr =
instead of justfubar
which looks weird and wrong. - 你不可能有空值,你可以,但是它们看起来像:fuabr =而不是fubar,看起来很奇怪而且错误。
#1
95
This can be something to start with:
这可以从以下几个方面开始:
import configparserconfig = configparser.ConfigParser()config.read('FILE.INI')print(config['DEFAULT']['path']) # -> "/path/name/"config['DEFAULT']['path'] = '/var/shared/' # updateconfig['DEFAULT']['default_message'] = 'Hey! help me!!' # createwith open('FILE.INI', 'w') as configfile: # save config.write(configfile)
You can find more at the official configparser documentation.
您可以在官方的configparser文档中找到更多信息。
#2
39
Here's a complete read, update and write example.
这里有一个完整的读、更新和写示例。
Input file, test.ini
输入文件,test.ini
[section_a]string_val = hellobool_val = falseint_val = 11pi_val = 3.14
Working code.
工作代码。
try: from configparser import ConfigParserexcept ImportError: from ConfigParser import ConfigParser # ver. < 3.0# instantiateconfig = ConfigParser()# parse existing fileconfig.read('test.ini')# read values from a sectionstring_val = config.get('section_a', 'string_val')bool_val = config.getboolean('section_a', 'bool_val')int_val = config.getint('section_a', 'int_val')float_val = config.getfloat('section_a', 'pi_val')# update existing valueconfig.set('section_a', 'string_val', 'world')# add a new section and some valuesconfig.add_section('section_b')config.set('section_b', 'meal_val', 'spam')config.set('section_b', 'not_found_val', 404)# save to a filewith open('test_update.ini', 'w') as configfile: config.write(configfile)
Output file, test_update.ini
输出文件,test_update.ini
[section_a]string_val = worldbool_val = falseint_val = 11pi_val = 3.14[section_b]meal_val = spamnot_found_val = 404
The original input file remains untouched.
原始输入文件保持原样。
#3
8
http://docs.python.org/library/configparser.html
http://docs.python.org/library/configparser.html
Python's standard library might be helpful in this case.
在这种情况下,Python的标准库可能会有帮助。
#4
2
The standard ConfigParser
normally requires access via config['section_name']['key']
, which is no fun. A little modification can deliver attribute access:
标准的ConfigParser通常要求通过config['section_name']['key']进行访问,这一点都不好玩。稍微修改一下就可以实现属性访问:
class AttrDict(dict): def __init__(self, *args, **kwargs): super(AttrDict, self).__init__(*args, **kwargs) self.__dict__ = self
AttrDict
is a class derived from dict
which allows access via both dictionary keys and attribute access: that means a.x is a['x']
AttrDict是一个派生自dict类型的类,它允许通过字典键和属性访问:即a。x是一个[' x ']
We can use this class in ConfigParser
:
我们可以在ConfigParser中使用这个类:
config = configparser.ConfigParser(dict_type=AttrDict)config.read('application.ini')
and now we get application.ini
with:
现在我们有了应用。ini:
[general]key = value
as
作为
>>> config._sections.general.key'value'
#5
2
ConfigObj is a good alternative to ConfigParser which offers a lot more flexibility:
ConfigObj是ConfigParser的一个很好的替代选择,它提供了更多的灵活性:
- Nested sections (subsections), to any level
- 嵌套节(子节),任何级别
- List values
- 列表值
- Multiple line values
- 多个线值
- String interpolation (substitution)
- 字符串插值(替换)
- Integrated with a powerful validation system including automatic type checking/conversion repeated sections and allowing default values
- 集成了一个强大的验证系统,包括自动类型检查/转换重复部分和允许默认值
- When writing out config files, ConfigObj preserves all comments and the order of members and sections
- 在编写配置文件时,ConfigObj保留所有注释和成员和部分的顺序。
- Many useful methods and options for working with configuration files (like the 'reload' method)
- 使用配置文件的许多有用的方法和选项(比如“reload”方法)
- Full Unicode support
- 完整的Unicode支持
It has some draw backs:
它有一些不足之处:
- You cannot set the delimiter, it has to be
=
… (pull request) - 不能设置分隔符,它必须是=…(拉请求)
- You cannot have empty values, well you can but they look liked:
fuabr =
instead of justfubar
which looks weird and wrong. - 你不可能有空值,你可以,但是它们看起来像:fuabr =而不是fubar,看起来很奇怪而且错误。