우리는 jproperties
모듈을 사용하여 Python에서 속성 파일을 읽을 수 있습니다. 속성 파일은 각 줄마다 키-값 쌍을 포함합니다. 등호(=)는 키와 값 사이의 구분자로 작동합니다. #으로 시작하는 줄은 주석으로 처리됩니다.
jproperties 라이브러리 설치
이 모듈은 표준 설치의 일부가 아닙니다. 우리는 PIP를 사용하여 jproperties 모듈을 설치할 수 있습니다.
# pip install jproperties
Python에서 속성 파일 읽기
I have created a properties file for our example: app-config.properties.
# Database Credentials
DB_HOST=localhost
DB_SCHEMA=Test
DB_User=root
DB_PWD=root@neon
# 데이터베이스 자격 증명
from jproperties import Properties
configs = Properties()
첫 번째 단계는 Properties 객체를 우리의 Python 프로그램으로 가져와 인스턴스화하는 것입니다.
with open('app-config.properties', 'rb') as config_file:
configs.load(config_file)
다음 단계는 속성 파일을 우리의 Properties 객체로 로드하는 것입니다.
추천 도서: Python with 문
지금은 get()
메서드를 사용하거나 인덱스를 통해 특정 속성을 읽을 수 있습니다. 속성 객체는 Python Dictionary와 매우 유사합니다.
print(configs.get("DB_User"))
값은 두 개의 값 - 데이터와 메타 - 의 명명된 튜플인 PropertyTuple 객체에 저장됩니다. jproperties는 속성 메타데이터도 지원하지만, 여기서는 관심이 없습니다.
print(f'Database User: {configs.get("DB_User").data}')
# PropertyTuple(data='root', meta={})
print(f'Database Password: {configs["DB_PWD"].data}')
# 데이터베이스 사용자: root
# 데이터베이스 비밀번호: root@neon
print(f'Properties Count: {len(configs)}')
len() 함수를 사용하여 속성의 개수를 얻을 수 있습니다.
# 속성 개수: 4
random_value = configs.get("Random_Key")
print(random_value) 키가 존재하지 않으면 get() 메서드가 None을 반환합니다.
# None
try:
random_value = configs["Random_Key"]
print(random_value)
except KeyError as ke:
print(f'{ke}, lookup key was "Random_Key"')
그러나 인덱스를 사용하면 KeyError
가 발생합니다. 이 경우 try-except 블록을 사용하여 이 예외를 처리하는 것이 좋습니다.
# 출력:
# ‘키를 찾을 수 없음’, 조회된 키는 “Random_Key”입니다
items_view = configs.items()
print(type(items_view))
for item in items_view:
print(item)
items() 메서드를 사용하여 튜플의 컬렉션을 얻을 수 있습니다. 이 튜플은 키와 해당하는 PropertyTuple 값이 포함되어 있습니다.
<class 'collections.abc.ItemsView'>
('DB_HOST', PropertyTuple(data='localhost', meta={}))
('DB_SCHEMA', PropertyTuple(data='Test', meta={}))
('DB_User', PropertyTuple(data='root', meta={}))
('DB_PWD', PropertyTuple(data='root@neon', meta={}))
출력:
for item in items_view:
print(item[0], '=', item[1].data)
우리는 출력으로 key=value를 출력하려고 하기 때문에 다음 코드를 사용할 수 있습니다.
DB_HOST = localhost
DB_SCHEMA = Test
DB_User = root
DB_PWD = root@neon
출력:
from jproperties import Properties
configs = Properties()
with open('app-config.properties', 'rb') as config_file:
configs.load(config_file)
items_view = configs.items()
list_keys = []
for item in items_view:
list_keys.append(item[0])
print(list_keys)
여기는 속성 파일을 읽고 모든 키의 리스트를 생성하는 완전한 프로그램입니다.
# [‘DB_HOST’, ‘DB_SCHEMA’, ‘DB_User’, ‘DB_PWD’]
A properties file is the same as a dictionary. So, it’s a common practice to read the properties file into a dictionary. The steps are similar to above, except for the change in the iteration code to add the elements to a dictionary.
db_configs_dict = {}
for item in items_view:
db_configs_dict[item[0]] = item[1].data
print(db_configs_dict)
파이썬 속성 파일을 딕셔너리로 읽기
# {‘DB_HOST’: ‘localhost’, ‘DB_SCHEMA’: ‘Test’, ‘DB_User’: ‘root’, ‘DB_PWD’: ‘root@neon’}
Source:
https://www.digitalocean.com/community/tutorials/python-read-properties-file