繁体   English   中英

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

[英]open files from another directory from python in 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     

├── share_dir
│   └── testing.txt     

├── scripts
│   └── python_wrapper.sh       

Run mechanism

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_helper.py contents

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_wrapper.sh时,我没有任何问题

sh /home/$USER/main_project/scripts/python_wrapper.sh test_job

当我像下面这样调用python_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

然后我收到NO file or directory main_project/share_dir/testing.txt error

从任何目录调用python_wrapper.sh时,我想毫无问题地读取testing.txt文件

我该如何解决这个问题

这从文件自己的位置(在助手内部)开始,并构造main_project的实际位置:

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

暂无
暂无

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

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