Home > Blockchain >  What is the alternative for text.properties in Python
What is the alternative for text.properties in Python

Time:01-20

I am looking for a way to move all the text strings to a separate file. This will help with making making international version.

It should work like hello_world.py

print(hello_statement)

and text.properties:

hello_statement=Hello world

What is the right way to implement it?

CodePudding user response:

One way to implement this would be to use a library like configparser to read in values from a properties file. You can then reference the values in your Python code. For example, you could create a file called text.properties with the following contents:

[Strings]
hello_statement = Hello world

In your Python code, you can use the configparser library to read in the values from the properties file:

import configparser

config = configparser.ConfigParser()
config.read('text.properties')

hello_statement = config['Strings']['hello_statement']
print(hello_statement)

CodePudding user response:

You could simply use .py files for the different languages. For example, you can have:

english.py:

hello_statement = "Hello World"

and spanish.py:

hello_statement = "Hola Mundo"

And now you can import the matching file according to the language:

lang = "es"
if lang == "en":
    from english import *
elif lang == "es":
    from spanish import *
else:
    raise ValueError("Unsupported language:", lang)

print(hello_statement)

CodePudding user response:

If you don't want to use additional libraries then this would work.

text.properties:

hello_statement=Hello world

Code:

# open the file
with open("text.properties") as f:
    data = f.readlines()

source_dict = {}

# parse the file
for line in data:
    k, v = line.split("=")
    source_dict[k] = v

# print function
def print_from_file(statement):
    print(source_dict[statement])

# use print function
print_from_file("hello_statement")

However, @tomerikoo's comment with the import statement looks most elegant :)

  • Related