简体   繁体   English

如何在不提供绝对路径的情况下访问PyDev项目资源目录中的文件?

[英]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. 我在Eclipse中有一个PyDev项目,其中包括“ src”目录和“ rsc”目录。

I would like to read/write files in the "rsc" dir. 我想在“ rsc”目录中读取/写入文件。 If i give for example the following command in .py file in the "src" dir: 例如,如果我在“ src”目录中的.py文件中给出以下命令:

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.) 我收到一条错误消息:“没有这样的文件:rsc / test.txt”,(给出绝对路径(即“ home /.../ test.txt”)是可行的。)

This works for java projects. 这适用于Java项目。 How can I do this for python projects? 如何为python项目执行此操作? 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" 为了澄清,我的目录结构如下:proj_dir-> src-> file.py,proj_dir-> rsc-> test.txt我正在src中运行文件,例如“ 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. 如果您的src和rsc目录共享同一个父目录,则这将始终有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何基于绝对路径访问完全不同目录中的文件(Python) - How can I access a file in a completely different directory based on absolute path (Python) 如何在Python中打印文件列表的绝对路径? - How can I print the absolute path of a list of files in Python? 我可以将Java文件放在pydev项目的文件夹中吗? - Can i put java files in a folder in a pydev project? 如何通过相对路径获取“其他”项目文件的绝对路径? - How to obtain absolute path via relative path for 'other' project files? 金字塔:如何对某个绝对路径进行静态查看,然后让用户将文件上传至该路径? - Pyramid: How can I making a static view to some absolute path, and then let users upload files to that path? Pydev相对项目路径 - Pydev relative project path 如何获得相对于项目根目录的绝对路径而没有双斜杠? - How to get the absolute path relative to the project root without double slashes? 如何在用户输入的子目录中访问文件而不必在Python 2.7.11中声明目录? - How do I access a file in a sub-directory on user input without having to state the directory in Python 2.7.11? PyDev中的PyLint仅分析最顶层项目目录中的文件 - PyLint in PyDev only analysing files in top-most project directory 获取子目录中文件的绝对路径 - Get absolute path of files in sub-directory
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM