1

I'm writing a graphical application which will depend on a language file containing text snippets in different languages for the UI elements.

I want to store these files in a lang/ directory inside the package directory which is imported by the main application script when executed.

However, I can't use ./ when opening the language files for reading, because ./ is the working directory of the user, not the location of the imported Python file.

With a source structure that looks like

/
-- mypkg/
   -- lang/
      -- en_US.lang
      -- es_ES.lang
      -- <etc...>
   -- __init__.py
   -- lang.py
-- myapp (executable Python script which imports mypkg)

how can I reliably read from the lang/ directory without relying on a particular working directory?

2mac
  • 1,269
  • 3
  • 15
  • 30

1 Answers1

3

You can use the variable - __file__ - this stores the path of the script which is being run. (This is the path which was used in the python command) , example if you used the following command to run the script -

python /complete/path/to/script.py

__file__ would contain '/complete/path/to/script.py' . If relative path was used, it would contain the relative path to script .

Using this , you should be able to load the language files.

You can also use the function - os.path.abspath() to get the absolute path of the script -

import os.path
os.path.abspath(__file__)
Anand S Kumar
  • 76,986
  • 16
  • 159
  • 156