파이썬3로 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!!' )
업데이트된 파일.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)
자세한 내용은 공식 구성 분석기 설명서에서 확인할 수 있습니다.
여기 완전한 읽기, 업데이트 및 쓰기 예제가 있습니다.
입력 파일, 테스트.이니
[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.이니
[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
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'
backup_message.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
ConfigObj는 훨씬 더 많은 유연성을 제공하는 ConfigParser의 좋은 대안입니다.
- 모든 수준으로 중첩된 섹션(하위 섹션)
- 값 나열
- 다중 선 값
- 문자열 보간(대체)
- 반복 섹션 자동 유형 확인/변환 및 기본값 허용을 포함한 강력한 검증 시스템과 통합
- 구성 파일을 작성할 때 ConfigObj는 모든 주석과 멤버 및 섹션의 순서를 유지합니다.
- 구성 파일 작업에 유용한 다양한 방법 및 옵션(예: '재로드' 방법)
- 전체 유니코드 지원
몇 가지 단점이 있습니다.
- 구분 기호를 설정할 수 없습니다. 구분 기호는 다음과 같아야 합니다.
=(추가 요청) - 빈 값은 사용할 수 없지만 다음과 같이 표시됩니다.
fuabr =의 대신에fubar이상하고 잘못된 것 같습니다.
구성 파서를 사용할 때 - 매개 변수에서 값을 가져오려고 할 때 오류가 발생했습니다.
대상=\my-server\backup$%사용자 이름 %
파서가 특수 문자 '%'로 이 값을 가져올 수 없기 때문입니다.그런 다음 '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)
사용할 수 있습니다.python-benedict다음과 같은 대부분의 일반적인 형식에 대해 표준화된 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)
테스트 및 문서화가 잘 되어 있으므로 README에서 모든 기능을 확인하십시오.
설명서: https://github.com/fabiocaccamo/python-benedict
설치:pip install python-benedict
참고: 이 프로젝트의 작성자입니다.
중첩된 사전을 사용합니다.확인:
INI 파일: 예.이니
[Section]
Key = Value
코드:
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"
다음과 같은 코드 적용:
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"
언급URL : https://stackoverflow.com/questions/8884188/how-to-read-and-write-ini-file-with-python3
'programing' 카테고리의 다른 글
| 다중 필드 mongo DB에서 정렬 (0) | 2023.05.13 |
|---|---|
| 실제 Azure 웹 사이트 배포 암호는 어디서 얻을 수 있습니까? (0) | 2023.05.13 |
| IBOutlet은 0이지만 스토리보드에 연결되어 있습니다. Swift (0) | 2023.05.13 |
| node.js에서 기본 표준 시간대를 설정하려면 어떻게 해야 합니까? (0) | 2023.05.13 |
| SQL JOIN 및 다양한 유형의 JOIN (0) | 2023.05.13 |