[python] 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']

이 클래스는 ConfigParser다음 에서 사용할 수 있습니다 .

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

이제 우리는 다음을 얻 application.ini습니다.

[general]
key = value

같이

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


답변

ConfigObj 는 훨씬 더 많은 유연성을 제공하는 ConfigParser의 좋은 대안입니다.

  • 모든 수준의 중첩 섹션 (하위 섹션)
  • 값 나열
  • 여러 줄 값
  • 문자열 보간 (대체)
  • 자동 유형 검사 / 반복 섹션 및 기본값 허용을 포함한 강력한 유효성 검사 시스템과 통합
  • 구성 파일을 작성할 때 ConfigObj는 모든 주석과 구성원 및 섹션의 순서를 유지합니다.
  • 구성 파일 작업을위한 많은 유용한 방법 및 옵션 (예 : ‘reload’방법)
  • 완전한 유니 코드 지원

몇 가지 단점이 있습니다.

  • 구분자를 설정할 수 없습니다. =… ( pull request ) 여야합니다 .
  • 당신은 빈 값을 가질 수 없습니다. 잘 할 수는 있지만 그들은 좋아 보입니다 : fuabr =단지 fubar이상하고 잘못된 것처럼 보입니다.

답변

backup_settings.ini 파일의 내용

[Settings]
year = 2020

읽기를위한 파이썬 코드

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

쓰기 또는 업데이트

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

산출

[Settings]
year = 2050
day = sunday


답변