Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python is throwing error for a file path inside the Project folder where it is not supposed to and seems to be a python glitch

Python is throwing some inconsistent error for a file reference inside the Project folder based on ‘Working Directory’ in the script configuration which is very weird

My Project Structure as follows

My Project Structure as follows

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

config_utils.py

f = ''

def config_init():

    global f

    txt_dir = '../files/sample.txt'

    f = open(txt_dir, "r")

    f = f.read()

mycode.py

import config_ru.config_utils as cu

cu.config_init()

print(cu.f)

On executing mycode.py, it throws the below error w.r.t "sample.txt" in "files" package

enter image description here

but if I change the Working directory of "my_code.py" in the script configuration from "level2" to "level1", mycode.py gets executed successfully

enter image description here

enter image description here

This is very weird because in both the cases the location of "sample.txt" remains unchanged and both the error and being forced to change the Working Directory seems to be unacceptable. Please clarify

>Solution :

The work-around is to get the path of the module you are in and apply the relative path of the resource file to that:

from pathlib import Path

f = ''

def config_init():
    global f

    p = Path(__file__).parent.absolute()
    txt_dir = (p / '../files/sample.txt').resolve()

    f = open(txt_dir, "r")
    f = f.read()
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading