0

My question is nearly identical to this existing question but I want to know if there is a way for the properties file to be read while preserving whitespace in the values. For the purposes of translating an i18n Java properties file to another language using Python, I want to read this example file messages.properties:

default.null.message=Property [{0}] of class [{1}] cannot be null
catalogItem.listRest.exception=Something went wrong while \
    searching for catalog items. \
    Please try again.
handshake.register.disabledException.error=User is disabled
sessionItemService.transferToInstructor.notAuthorizedToTeach={0} is not authorized \
    to teach {1}

I am able to do so with the following Python code:

import configparser


input_file_path = "messages.properties"
# Open the file in read mode to read its contents
with open(input_file_path, 'r', encoding='utf-8') as f:
    file_contents = f.readlines()

# Insert an ini section at the beginning of the file contents so it can be read by configparser
file_contents.insert(0, "[default]\n")

# Open the file in write mode to write the updated contents
with open(input_file_path, 'w', encoding='utf-8') as f:
    f.writelines(file_contents)

# Parse the properties file
config = configparser.ConfigParser()
config.read(input_file_path)

# Remove the ini section from file contents by slicing the list
file_contents = file_contents[1:]

# Open the file in write mode to once again write the updated contents
with open(input_file_path, 'w', encoding='utf-8') as f:
    f.writelines(file_contents)

for key in config['default']:
    translation = config.get('default', key)
    print(f'{translation}\n')

Which outputs:

Property [{0}] of class [{1}] cannot be null

Something went wrong while \
searching for catalog items. \
Please try again.

User is disabled

{0} is not authorized \
to teach {1}

But is there a way I could have it preserve the whitespace in the values and output this instead?

Property [{0}] of class [{1}] cannot be null

Something went wrong while \
    searching for catalog items. \
    Please try again.

User is disabled

{0} is not authorized \
    to teach {1}

wubbalubba
  • 535
  • 2
  • 15

0 Answers0