slmnkhokhar
slmnkhokhar

Reputation: 97

How can I access files in resource directory of a PyDev project without having to give absolute path?

I have a PyDev project in eclipse consisting of a "src" directory and an "rsc" directory.

I would like to read/write files in the "rsc" dir. If i give for example the following command in .py file in the "src" dir:

numpy.savetxt("rsc/test.txt", temp, fmt='%3.15f', delimiter=' ')

I get an error saying "No such file: rsc/test.txt", (Giving the absolute path (i-e "home/.../test.txt") works.)

This works for java projects. How can I do this for python projects? Is this problem specific to eclipse?

To clarify, my dir structure is as follows: proj_dir -> src -> file.py, proj_dir -> rsc -> test.txt I am running a file in src e-g "file.py"

Upvotes: 0

Views: 785

Answers (1)

Tony Suffolk 66
Tony Suffolk 66

Reputation: 9704

instead of using :

numpy.savetxt("rsc/test.txt", temp, fmt='%3.15f', delimiter=' ')

you can use :

import os, inspect
this_file = os.path.abspath(inspect.getfile(inspect.currentframe()))

project_dir = os.path.dirname(os.path.dirname(this_file))
numpy.savetext(os.path.join(project_dir,"rsc/test.txt"), temp, fmt='%3.15f', delimiter=' ')

This will always work if your src and rsc directories share the same parent.

Upvotes: 1

Related Questions