0

When a Python project gets big, certain code segments, such as utility functions, tend to be run from various locations:

  • from a __main__
  • from a django server process
  • from a test in a test suite

In each case the working directory for the python interpreter may be different and assuming the project spans over a sub-directory tree, the following line doesn't always work:

with open('some_file.xml','r') as my_xml:

It doesn't work because some_file.xml isn't always in your working directory. You need to be specific regarding the file's location, however, the project may be deployed in various environments so simply adding the directory to the open statement isn't a good solution.

What would be an elegant and efficient way to "lock on" the location of the file throughout the project?

Jonathan Livni
  • 101,334
  • 104
  • 266
  • 359
  • Notice that a configuration file would suffer the same ill fate as the xml file - it's a resource which doesn't always exist in the same working directory... – Jonathan Livni Aug 29 '11 at 12:50
  • The difference between my question and [this question](http://stackoverflow.com/questions/1967688/accessing-a-file-relatively-in-python-if-you-do-not-know-your-starting-point) is that the code can't assume a priori what the working directory is within the project directory structure – Jonathan Livni Aug 29 '11 at 13:00

1 Answers1

1

using the following variable to get the directory of the project may help

 __file__ 

How to make a python program path independent?

Community
  • 1
  • 1
jknair
  • 4,709
  • 1
  • 17
  • 20
  • Although I don't want to assume anything about the working directory, your suggestion will work, because: I do need the project's root in the PYTHONPATH anyway, therefore I can always reach the files at the root of the project and there `__file__` can be used - thanks! – Jonathan Livni Aug 29 '11 at 13:10
  • [This answer](http://stackoverflow.com/questions/1967688/accessing-a-file-relatively-in-python-if-you-do-not-know-your-starting-point/1967692#1967692) also helps with how to use `__file__` – Jonathan Livni Aug 29 '11 at 13:11
  • or else you can always use a properties file with setup specific filePaths and load according to the setup on which the app is deployed. wrt JAVA : maven lets you create profiles of various setups which can be used as placeholders in the properties file that get replaced on each build. I think distutils lets you do the same for python – jknair Aug 29 '11 at 13:16