Programing

Python3으로 INI 파일을 읽고 쓰는 방법은 무엇입니까?

lottogame 2020. 8. 26. 08:18
반응형

Python3으로 INI 파일을 읽고 쓰는 방법은 무엇입니까?


Python3으로 INI 파일 을 읽고, 쓰고, 만들어야합니다 .

FILE.INI

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

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!!' )

업데이트 된 FILE.INI

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

다음으로 시작할 수 있습니다.

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)

공식 configparser 문서 에서 더 많은 정보를 찾을 수 있습니다 .


여기에 완전한 읽기, 업데이트 및 쓰기 예제가 있습니다.

입력 파일, 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

원래 입력 파일은 그대로 유지됩니다.


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

이 경우 Python의 표준 라이브러리가 도움이 될 수 있습니다.


표준은 ConfigParser일반적으로를 통해 액세스해야 config['section_name']['key']하며 이는 재미가 없습니다. 약간의 수정으로 속성 액세스를 제공 할 수 있습니다.

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

AttrDictdict사전 키와 속성 액세스를 통해 액세스를 허용하는 파생 된 클래스 입니다. 즉,a.x is a['x']

We can use this class in ConfigParser:

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

and now we get application.ini with:

[general]
key = value

as

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

ConfigObj is a good alternative to ConfigParser which offers a lot more flexibility:

  • 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
  • Many useful methods and options for working with configuration files (like the 'reload' method)
  • Full Unicode support

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.

참고URL : https://stackoverflow.com/questions/8884188/how-to-read-and-write-ini-file-with-python3

반응형