代码之家  ›  专栏  ›  技术社区  ›  nmr

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

  •  0
  • nmr  · 技术社区  · 5 年前

    我有个文件在里面 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
    

    蟒蛇_包装器.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

    测试.txt 调用 蟒蛇_包装器.sh 从任何目录

    1 回复  |  直到 5 年前
        1
  •  1
  •   Tim Roberts    5 年前

    这从文件本身的位置(在helper中)开始,并构造文件的实际位置 main_project :

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