在linux中从python的另一个目录打开文件

在linux中从python的另一个目录打开文件,python,linux,Python,Linux,我在Linux中有一个名为testing.txt的文件 下面是我在Linux main_project ├── base_dir │ └── helper │ └── file_helper.py │ └── __init__.py └── jobs └── adhoc_job.py └── __init__.py └── test_job.py └── __init__.py ├─

我在
Linux
中有一个名为
testing.txt
的文件

下面是我在
Linux

main_project
├── base_dir
│   └── helper
│       └── file_helper.py
│       └── __init__.py
    └── jobs
        └── adhoc_job.py
        └── __init__.py

        └── test_job.py
        └── __init__.py     

├── share_dir
│   └── testing.txt     

├── scripts
│   └── python_wrapper.sh       
运行机制

1) Using python_wrapper.sh I will run the `jobs/test_job.py` script. 
2) In jobs/test_job.py I have from helper.file_helper import *
3) In helper/file_helper.py I will read the testing.txt file
helper/file\u helper.py内容

print(os.getcwd())

with open("main_project/share_dir/testing.txt") as f:
    data = {}
    for line in f:
        key,value = line.strip().split('#')
        data[key] = value
        
当我像下面那样调用
python\u wrapper.sh
时,我没有任何问题

sh /home/$USER/main_project/scripts/python_wrapper.sh test_job
当我调用
python\u wrapper.sh
时,如下所示

# change directory to main_project(this is not in python_wrapper.sh)
cd main_project

# run the scripts
sh scripts/python_wrapper.sh test_job
然后我得到
无文件或目录main\u project/share\u dir/testing.txt错误

当从任何目录调用
python\u wrapper.sh
时,我希望读取
testing.txt
文件时不会出现任何问题


如何解决此问题

这将从文件自身的位置(在帮助器内部)开始,并构建
主\u项目的实际位置

mainproj = os.path.realpath( os.path.dirname(__file__)+"/../.." )
with open( mainproj + "/share_dir/testing.text") as f:

你明白为什么会出现这个错误吗?您当前的目录是
main\u project
,您正试图从里面打开一个
main\u project
。你需要决定“规则”是什么。如果规则是当前目录始终位于
main\u project
之上,则需要从
python\u wrapper.sh
中删除
cd
。如果希望脚本从任何地方启动,则需要构造路径。我会把它写在回答中。