Python get multiline value from properties file
The properties file is quite identical to an INI file.
You can use configparser with a fake section to easily parse it:
data = r"""first.key=\
Right,\
Side,\
Value
second.key=Second value
third.key=Third value"""
import configparser
def read_properties(data: str):
config = configparser.ConfigParser()
config.read_string("[dummysection]\n" + data)
return dict(config['dummysection'])
print(read_properties(data))
Output:
{'first.key': '\\\nRight,\\\nSide,\\\nValue', 'second.key': 'Second value', 'third.key': 'Third value'}
If you wish, you can further process it to remove the \\\n
:
print({k: v.replace("\\\n", "") for k, v in read_properties(data).items()})
Output:
{'first.key': 'Right,Side,Value', 'second.key': 'Second value', 'third.key': 'Third value'}
If you don't want to use config parser, I wrote a custom parser
import re
with open('delete.txt', "r") as file:
data = file.read()
# parsed_data = data.split('=')
parsed_data = re.split('(?<=[^\\\\])\n', data)
data_dict = {}
for element in parsed_data:
split = element.split('=')
data_dict[split[0]] = split[1].split('\\\n')
for key in data_dict:
print(f"{key} : {data_dict[key]}")
The output:
first.key : ['', ' Right,', ' Side,', ' Value']
second.key : ['Second value']
third.key : ['Third value']
This parser can definitely be improved. But I'd say the hard part has been taken care of
The input file:
first.key=\
Right,\
Side,\
Value
second.key=Second value
third.key=Third value