1

I want to have a textfile with all the text in it,which is represented in the program, to make it easy to translate my program into another language. I could use a normal list but then it would be very hard to see which text would be represented when looking into the code.

text file:

here is the text represented in the running program
inside the code you cant say whats written right here

code:

language_file = open("file.txt", "r", encoding="utf-8")
language_list = storage_file.readlines()
print(language_list[1])

I hope you can understand my problem with that ^ Instead of using a list, I want to use a dictionary. And the file then should look something like this:

"some_shortcut_to_remind_me_whats_happening": "Text in another language"
"another_shortcut": "Now I know whats written right here"

the code then could look like this:

print(language_dict["another_shortcut"])

But I dont know how to get a dictionary out of a textfile

Philipp
  • 93
  • 8

3 Answers3

3

Why not just save the file in json? It's still easy to read and you could have multiple languages in one file too:

Example:

File.json contains:

{
  "en": 
    {
      "some_shortcut_to_remind_me_whats_happening": "Text in another language",
      "another_shortcut": "Now I know whats written right here"
    }
}

And your code will be something like:

import json

with open("file.json", "r") as f:
    json = json.load(f)

print(json["en"]["some_shortcut_to_remind_me_whats_happening"])
H4CKY
  • 564
  • 4
  • 12
  • 1
    This is the right answer. JSON exists for a reason. Small improvement would be to do `with open("file.json", "r") as f:\n\tjson = json.load(f)`. – pzp Jun 16 '17 at 15:21
  • Thanks @pzp, fixed it :) – H4CKY Jun 17 '17 at 14:56
0

If you don't want to use external libraries and have your file formatted as follows:

key1: value1
key2: value2
.....

You can use:

with open(filename, 'r') as f:
    my_dict = dict((key, value.strip())
                   for key, value in (line.split(':') for line in f))
Szymon
  • 460
  • 6
  • 17
0

What you describe looks like a CSV file where the delimiter is : and using " as quote (the default). You could easily build your lookup table that way:

language_dict = {}
with open("file.txt", "r", encoding="utf-8", newline='') as language_file:
    reader = csv.reader(language_file, delimiter=':', skipinitialspace=True)
    for row in reader:
        language_dict[row[0]] = row[1]

NB: this syntax is only valid for Python3, unfortunately, the opening of a file to be used for csv is different between Python2 and Python3. In Python2 first line would be:

with open("file.txt", "rb") as language_file:
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252