简体   繁体   中英

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 (ie "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 eg "file.py"

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM