简体   繁体   English

如何用Python3读写INI文件?

[英]How to read and write INI file with Python3?

I need to read, write and create an INI file with Python3.我需要使用 Python3 读取、写入和创建INI文件。

FILE.INI文件.INI

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

Python File: 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!!' )

UPDATED FILE.INI更新的FILE.INI

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

This can be something to start with:这可以是开始的事情:

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)

You can find more at the official configparser documentation .您可以在官方 configparser 文档中找到更多信息

Here's a complete read, update and write example.这是一个完整的读取、更新和写入示例。

Input file, test.ini输入文件,test.ini

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

Working code.工作代码。

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)

Output file, test_update.ini输出文件,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

The original input file remains untouched.原始输入文件保持不变。

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 的标准库可能会有所帮助。

The standard ConfigParser normally requires access via config['section_name']['key'] , which is no fun.标准的ConfigParser通常需要通过config['section_name']['key'] ,这并不好玩。 A little modification can deliver attribute access:稍加修改即可提供属性访问:

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 ax is a['x'] AttrDict是派生自dict的类,它允许通过字典键和属性访问进行访问:这意味着ax is a['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:现在我们得到application.ini

[general]
key = value

as作为

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

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)许多处理配置文件的有用方法和选项(如“重新加载”方法)
  • 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 just fubar which looks weird and wrong.你不能有空值,你可以,但它们看起来很喜欢: fuabr =而不仅仅是fubar看起来很奇怪和错误。

contents in my backup_settings.ini file我的backup_settings.ini文件中的内容

[Settings]
year = 2020

python code for reading用于阅读的python代码

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

for writing or updating用于写作或更新

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"))

output输出

[Settings]
year = 2050
day = sunday

There are some problems I found when used configparser such as - I got an error when I tryed to get value from param:我在使用 configparser 时发现了一些问题,例如 - 当我尝试从 param 获取值时出现错误:

destination=\\my-server\\backup$%USERNAME%目的地=\\my-server\\backup$%USERNAME%

It was because parser can't get this value with special character '%'.这是因为解析器无法使用特殊字符 '%' 获取此值。 And then I wrote a parser for reading ini files based on 're' module:然后我写了一个解析器来读取基于 're' 模块的 ini 文件:

import re

# read from ini file.
def ini_read(ini_file, key):
    value = None
    with open(ini_file, 'r') as f:
        for line in f:
            match = re.match(r'^ *' + key + ' *= *.*$', line, re.M | re.I)
            if match:
                value = match.group()
                value = re.sub(r'^ *' + key + ' *= *', '', value)
                break
    return value


# read value for a key 'destination' from 'c:/myconfig.ini'
my_value_1 = ini_read('c:/myconfig.ini', 'destination')

# read value for a key 'create_destination_folder' from 'c:/myconfig.ini'
my_value_2 = ini_read('c:/myconfig.ini', 'create_destination_folder')


# write to an ini file.
def ini_write(ini_file, key, value, add_new=False):
    line_number = 0
    match_found = False
    with open(ini_file, 'r') as f:
        lines = f.read().splitlines()
    for line in lines:
        if re.match(r'^ *' + key + ' *= *.*$', line, re.M | re.I):
            match_found = True
            break
        line_number += 1
    if match_found:
        lines[line_number] = key + ' = ' + value
        with open(ini_file, 'w') as f:
            for line in lines:
                f.write(line + '\n')
        return True
    elif add_new:
        with open(ini_file, 'a') as f:
            f.write(key + ' = ' + value)
        return True
    return False


# change a value for a key 'destination'.
ini_write('my_config.ini', 'destination', '//server/backups$/%USERNAME%')

# change a value for a key 'create_destination_folder'
ini_write('my_config.ini', 'create_destination_folder', 'True')

# to add a new key, we need to use 'add_new=True' option.
ini_write('my_config.ini', 'extra_new_param', 'True', True)

Use nested dictionaries.使用嵌套字典。 Take a look:看一看:

INI File: example.ini INI 文件:example.ini

[Section]
Key = Value

Code:代码:

class IniOpen:
    def __init__(self, file):
        self.parse = {}
        self.file = file
        self.open = open(file, "r")
        self.f_read = self.open.read()
        split_content = self.f_read.split("\n")

        section = ""
        pairs = ""

        for i in range(len(split_content)):
            if split_content[i].find("[") != -1:
                section = split_content[i]
                section = string_between(section, "[", "]")  # define your own function
                self.parse.update({section: {}})
            elif split_content[i].find("[") == -1 and split_content[i].find("="):
                pairs = split_content[i]
                split_pairs = pairs.split("=")
                key = split_pairs[0].trim()
                value = split_pairs[1].trim()
                self.parse[section].update({key: value})

    def read(self, section, key):
        try:
            return self.parse[section][key]
        except KeyError:
            return "Sepcified Key Not Found!"

    def write(self, section, key, value):
        if self.parse.get(section) is  None:
            self.parse.update({section: {}})
        elif self.parse.get(section) is not None:
            if self.parse[section].get(key) is None:
                self.parse[section].update({key: value})
            elif self.parse[section].get(key) is not None:
                return "Content Already Exists"

Apply code like so:像这样应用代码:

ini_file = IniOpen("example.ini")
print(ini_file.parse) # prints the entire nested dictionary
print(ini_file.read("Section", "Key") # >> Returns Value
ini_file.write("NewSection", "NewKey", "New Value"

You could use python-benedict , it's a dict subclass that provides normalized I/O support for most common formats, including ini .您可以使用python-benedict ,它是一个 dict 子类,为大多数常见格式提供规范化的 I/O 支持,包括ini

from benedict import benedict

# path can be a ini string, a filepath or a remote url
path = 'path/to/config.ini'

d = benedict.from_ini(path)

# do stuff with your dict
# ...

# write it back to disk
d.to_ini(filepath=path)

It's well tested and documented, check the README to see all the features:它经过良好的测试和记录,检查自述文件以查看所有功能:

Documentation: https://github.com/fabiocaccamo/python-benedict文档: https : //github.com/fabiocaccamo/python-benedict

Installation: pip install python-benedict安装: pip install python-benedict

Note: I am the author of this project注意:我是这个项目的作者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM