如何使用Python3读写INI文件?

问题描述:

我需要使用Python3读取,编写和创建一个INI文件。如何使用Python3读写INI文件?

FILE.INI

default_path = "/path/name/" 
default_file = "file.txt" 

Python的文件:

# read file and if not exists 
ini = iniFile('FILE.INI') 

# Get and Print Config Line "default_path" 
getLine = ini.default_path 

# Print (string)/path/name 
print getLine 

# Append new line and if exists edit this line 
ini.append('default_path' , 'var/shared/') 

ini.append('default_message' , 'Hey! help me!!') 

UPDATE FILE.INI

default_path = "var/shared/" 
default_file = "file.txt" 
default_message = "Hey! help me!!" 
+4

http://docs.python.org/library/configparser.html? – 2012-01-16 17:57:30

+2

其实,http://stackoverflow.com/a/3220891/716118怎么样? – voithos 2012-01-16 18:01:01

这可有得开始:

import configparser 

config = configparser.ConfigParser() 
config.read('FILE.INI') 
print(config['DEFAULT']['path'])  # -> "/path/name/" 
config['DEFAULT']['path'] = '/var/shared/' # update 
config['DEFAULT']['default_message'] = 'Hey! help me!!' # create 

with open('FILE.INI', 'w') as configfile: # save 
    config.write(configfile) 

你可以找到更多的official configparser documentation

http://docs.python.org/library/configparser.html

Python的标准库在这种情况下可能会有帮助。

这是一个完整的读取,更新和写入示例。

输入文件,test.ini

[section_a] 
string_val = hello 
bool_val = false 
int_val = 11 
pi_val = 3.14 

工作代码。

try: 
    from configparser import ConfigParser 
except ImportError: 
    from ConfigParser import ConfigParser # ver. < 3.0 

# instantiate 
config = ConfigParser() 

# parse existing file 
config.read('test.ini') 

# read values from a section 
string_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 value 
config.set('section_a', 'string_val', 'world') 

# add a new section and some values 
config.add_section('section_b') 
config.set('section_b', 'meal_val', 'spam') 
config.set('section_b', 'not_found_val', 404) 

# save to a file 
with open('test_update.ini', 'w') as configfile: 
    config.write(configfile) 

输出文件,test_update.ini

[section_a] 
string_val = world 
bool_val = false 
int_val = 11 
pi_val = 3.14 

[section_b] 
meal_val = spam 
not_found_val = 404 

原始输入文件保持不变。

标准ConfigParser通常需要通过config['section_name']['key']访问,这是没有趣。稍加修改可以提供属性的访问:

class AttrDict(dict): 
    def __init__(self, *args, **kwargs): 
     super(AttrDict, self).__init__(*args, **kwargs) 
     self.__dict__ = self 

AttrDict是从dict派生的类,它允许经由两个字典键访问和属性访问:这意味着a.x is a['x']

我们所用ConfigParser使用这个类:

config = configparser.ConfigParser(dict_type=AttrDict) 
config.read('application.ini') 

,现在我们得到application.ini有:

[general] 
key = value 

>>> config._sections.general.key 
'value' 
+2

不错的诀窍,但这种方法的用户应该小心,当访问像''config._sections.general.key =“3”''这不会改变配置选项的内部值,因此只能使用为只读访问。如果在''.read()''命令之后配置被扩展或改变(为某些部分添加选项,值对, - >其中插值可能非常重要),则不应使用此访问方法!另外,对私有的''config._sections [“section”] [“opt”]''进行任何访问都会绕开插值并返回原始值! – Gabriel 2015-05-06 15:06:15

ConfigObj是ConfigParser一个很好的选择,它提供了更大的灵活性:

  • 嵌套的区段(小节),任何级别
  • 值列表
  • 多行值
  • 字符串插值(替代)
  • 集成了强大的验证系统包括自动类型检查/转换重复部分并允许默认值
  • 当写出配置文件,ConfigObj保留
  • 许多有用的方法和选择工作的所有意见和成员的顺序和部分使用配置文件(如 '刷新' 方法)
  • 完整的Unicode支持

它有一些抽奖背上:

  • 您不能设置分隔符,它必须是= ...(pull request
  • 你不能为空值,那么你可以,但他们看起来喜欢:fuabr =,而不是仅仅fubar这看起来奇怪,是错误的。
+1

Sardathrion是正确的,ConfigObj是如果你想保留文件中的注释和原始文件中的部分顺序的路。 ConfigParser只会清除您的意见,并会在某些时候对订单进行争夺。 – Arise 2016-10-11 07:20:12