如何用Python3读写INI文件?

Jor*_*sen 100 python ini python-3.x

我需要使用Python3 读取,编写和创建一个INI文件.

FILE.INI

default_path = "/path/name/"
default_file = "file.txt"
Run Code Online (Sandbox Code Playgroud)

Python文件:

#    Read file and and create if it not exists
config = iniFile( 'FILE.INI' )

#    Get "default_path"
config.default_path

#    Print (string)/path/name
print config.default_path

#    Create or Update
config.append( 'default_path', 'var/shared/' )
config.append( 'default_message', 'Hey! help me!!' )
Run Code Online (Sandbox Code Playgroud)

更新的 FILE.INI

default_path    = "var/shared/"
default_file    = "file.txt"
default_message = "Hey! help me!!"
Run Code Online (Sandbox Code Playgroud)

Rik*_*ggi 126

这可以从一开始:

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)
Run Code Online (Sandbox Code Playgroud)

您可以在官方的configparser文档中找到更多信息.

  • 当使用提供的示例文件而没有正确的节头时,给出configparser.MissingSectionHeaderError。 (3认同)

Ago*_*ino 68

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

输入文件test.ini

[section_a]
string_val = hello
bool_val = false
int_val = 11
pi_val = 3.14
Run Code Online (Sandbox Code Playgroud)

工作代码.

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)
Run Code Online (Sandbox Code Playgroud)

输出文件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
Run Code Online (Sandbox Code Playgroud)

原始输入文件保持不变.


小智 8

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

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


RK-*_*God 8

我的backup_settings.ini文件中的内容

[Settings]
year = 2020
Run Code Online (Sandbox Code Playgroud)

用于阅读的python代码

import configparser
config = configparser.ConfigParser()
config.read('backup_settings.ini') #path of your .ini file
year = config.get("Settings","year") 
print(year)
Run Code Online (Sandbox Code Playgroud)

用于写作或更新

from pathlib import Path
import configparser
myfile = Path('backup_settings.ini')  #Path of your .ini file
config.read(myfile)
config.set('Settings', 'year','2050') #Updating existing entry 
config.set('Settings', 'day','sunday') #Writing new entry
config.write(myfile.open("w"))
Run Code Online (Sandbox Code Playgroud)

输出

[Settings]
year = 2050
day = sunday
Run Code Online (Sandbox Code Playgroud)


Rob*_*mer 7

该标准ConfigParser通常需要通过 访问config['section_name']['key'],这并不有趣。稍加修改即可提供属性访问:

class AttrDict(dict):
    def __init__(self, *args, **kwargs):
        super(AttrDict, self).__init__(*args, **kwargs)
        self.__dict__ = self
Run Code Online (Sandbox Code Playgroud)

AttrDict是一个派生自dict它的类,允许通过字典键和属性访问进行访问:这意味着a.x is a['x']

我们可以在ConfigParser

config = configparser.ConfigParser(dict_type=AttrDict)
config.read('application.ini')
Run Code Online (Sandbox Code Playgroud)

现在我们得到application.ini

[general]
key = value
Run Code Online (Sandbox Code Playgroud)

作为

>>> config._sections.general.key
'value'
Run Code Online (Sandbox Code Playgroud)

  • 不错的技巧,但这种方法的用户应该注意,当访问像``config._sections.general.key = "3"`` 这不会改变配置选项的内部值,因此只能用于只读访问。如果在``.read()`` 命令之后配置被扩展或更改(为某些部分添加选项、值对,-&gt; 可能非常重要的插值)不应使用此访问方法!此外,对 ``config._sections["section"]["opt"]`` 的任何访问都可以绕过插值并返回原始值! (7认同)

Sar*_*ica 6

ConfigObj是 ConfigParser 的一个很好的替代品,它提供了更多的灵活性:

  • 嵌套部分(子部分),到任何级别
  • 列出值
  • 多行值
  • 字符串插值(替换)
  • 与强大的验证系统集成,包括自动类型检查/转换重复部分并允许默认值
  • 写出配置文件时,ConfigObj 保留所有注释以及成员和部分的顺序
  • 许多处理配置文件的有用方法和选项(如“重新加载”方法)
  • 完整的 Unicode 支持

它有一些缺点:

  • 您不能设置分隔符,它必须是=……(拉取请求
  • 你不能有空值,你可以,但它们看起来很喜欢:fuabr =而不是fubar看起来很奇怪和错误。

  • Sardathrion 是对的,如果您想将注释保留在文件中并保留原始文件中的节顺序,那么 ConfigObj 就是您的最佳选择。ConfigParser 只会清除您的注释,并且还会在某个时候打乱顺序。 (2认同)