-1

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

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

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
rams
  • 139
  • 1
  • 11

2 Answers2

2

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()
quamrana
  • 37,849
  • 12
  • 53
  • 71
1

Looks like normal behavior. In the line

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

the .. means 'go one directory up'. So, when you are in level2, it will go up one level (to level1) and look for files/sample.txt, which does not exist. However, when you are in level1, then the .. will bring you to the pythonProject dir, where it can find files/sample.txt

AndrzejO
  • 1,502
  • 1
  • 9
  • 12
  • oh thanks for the clarification. Actually i thought '..' means project root folder. What is the generic way to specify the project root folder rather giving abs path because if I may have to use the project in a different system . I want to let the code know that "sample.txt" is in the root folder / files. Please help – rams Sep 25 '22 at 19:31