웹사이트 검색

Python에서 속성 파일을 읽는 방법?


jproperties 모듈을 사용하여 Python에서 속성 파일을 읽을 수 있습니다. 속성 파일에는 각 줄에 키-값 쌍이 포함되어 있습니다. 등호(=)는 키와 값 사이의 구분 기호로 작동합니다. #으로 시작하는 줄은 주석으로 처리됩니다.

jproperties 라이브러리 설치

이 모듈은 표준 설치의 일부가 아닙니다. PIP를 사용하여 jproperties 모듈을 설치할 수 있습니다.

# pip install jproperties

Python에서 속성 파일 읽기

예제에 대한 속성 파일을 만들었습니다: app-config.properties.

# Database Credentials
DB_HOST=localhost
DB_SCHEMA=Test
DB_User=root
DB_PWD=root@neon

첫 번째 단계는 Properties 개체를 Python 프로그램으로 가져와서 인스턴스화하는 것입니다.

from jproperties import Properties

configs = Properties()

다음 단계는 속성 파일을 속성 개체에 로드하는 것입니다.

with open('app-config.properties', 'rb') as config_file:
    configs.load(config_file)

추천 도서: Python with Statement

이제 get() 메서드를 사용하거나 인덱스를 통해 특정 속성을 읽을 수 있습니다. Properties 객체는 Python Dictionary와 매우 유사합니다.

값은 PropertyTuple 개체에 저장되며 이는 데이터와 메타라는 두 값의 명명된 튜플입니다. jproperties는 속성 메타데이터도 지원하지만 여기서는 관심이 없습니다.

print(configs.get("DB_User"))  
# PropertyTuple(data='root', meta={})

print(f'Database User: {configs.get("DB_User").data}')  
# Database User: root

print(f'Database Password: {configs["DB_PWD"].data}')  
# Database Password: root@neon

len() 함수를 사용하여 속성 수를 얻을 수 있습니다.

print(f'Properties Count: {len(configs)}')  
# Properties Count: 4

키가 존재하지 않으면 어떻게 됩니까?

키가 존재하지 않으면 get() 메서드는 None을 반환합니다.

random_value = configs.get("Random_Key")
print(random_value)  # None

그러나 인덱스를 사용하면 KeyError가 발생합니다. 이 경우 try-except 블록을 사용하여 이 예외를 처리하는 것이 좋습니다.

try:
    random_value = configs["Random_Key"]
    print(random_value)
except KeyError as ke:
    print(f'{ke}, lookup key was "Random_Key"')

# Output:
# 'Key not found', lookup key was "Random_Key"

모든 속성 인쇄

items() 메서드를 사용하여 키와 해당 PropertyTuple 값을 포함하는 Tuple 컬렉션을 가져올 수 있습니다.

items_view = configs.items()
print(type(items_view))

for item in items_view:
    print(item)

산출:

<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={}))

출력으로 key=value를 인쇄하려고 하므로 다음 코드를 사용할 수 있습니다.

for item in items_view:
    print(item[0], '=', item[1].data)

산출:

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

Python은 속성 파일을 사전으로 읽기

속성 파일은 사전과 동일합니다. 따라서 속성 파일을 사전으로 읽는 것이 일반적입니다. 요소를 사전에 추가하는 반복 코드의 변경을 제외하고 단계는 위와 유사합니다.

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'}

참조: PyPI jproperties 페이지