0

I have a project folder, PythonProject. Within that Project folder I have a 2 subdirectories: SubDirectory & DataSubDirectory.

Within SubDirectory, I have a python file, TestFile.py which opens an external file, datafile.txt, contained in DataSubDirectory.

Currently, I open this file as such; open(..\\DataSubDirectory\\data.txt)

Is there a method by which I can set any file paths within my TestFile.py to be relative to the parent project folder, so that if the file were moved to another Sub Directory, or placed in the parent directory even, I would not get a filepath error? The effect being that any file opened as such; open(data\\data.txt) would actually be opened as open(PythonProject\\data\\data.txt), and not relative to whichever directory it is found?

alphazwest
  • 3,483
  • 1
  • 27
  • 39
  • See the answer to this question: http://stackoverflow.com/questions/1270951/python-how-to-refer-to-relative-paths-of-resources-when-working-with-code-repo – Hopeless Jul 18 '16 at 14:40

2 Answers2

1

If you are running from Project folder, set a variable(PRJ_PATH) to os.getcwd() and use it for opening the file like open(os.path.join(PRJ_PATH, 'data', 'data.txt'))

If you are running from subdirectories, set a variable(PRJ_PATH) to os.path.join(os.getcwd(), '..') and then use it for opening the file like open(os.path.join(PRJ_PATH, 'data', 'data.txt'))

be_good_do_good
  • 4,311
  • 3
  • 28
  • 42
  • Thank you, this method worked fine. The following usage seems to address my concern: `projectpath = os.path.join(os.getcwd(), '..', '..')` `file = open(os.path.join(projectpath, 'DataSubDirectory', 'data.txt'))` which successfully opens a file from a folder two directories above. – alphazwest Jul 18 '16 at 15:14
0

You can use PythonProject = os.path.dirname(os.path.realpath(sys.argv[0])) to set the PythonProject Path

BChow
  • 471
  • 2
  • 7