0

How can I read the /billy/var/text.txt into b.py

The directory structure is:

/billy/b.py
/billy/var/text.txt
/sally/s.py

s.py

import sys, os
sys.path.append('..')
from billy import b

print('s.py - ' + os.path.dirname(sys.argv[0]))

b.py

import sys, os

print('b.py - ' + os.path.dirname(sys.argv[0]))
ag = open(os.path.dirname(sys.argv[0]) + '//var//text.txt').read()
martineau
  • 119,623
  • 25
  • 170
  • 301
Rhys
  • 4,926
  • 14
  • 41
  • 64
  • Note: 'imports' usually refer to modules imported with the `import` statement. See the duplicate on how to get the absolute path of the current script, and from there, a path to anything relative from that position. – Martijn Pieters May 12 '18 at 18:54
  • Thank you for your response. I followed the link to the solution provided. `dirname = os.path.dirname(__file__)` returns `G:/tst/sally` ... `filename = os.path.join(dirname, 'relative/path/to/file/you/want')` cannot access **b.py** because **b.py** is `G:/tst/betty/b.py` ... one step back in the hierarchy. – Rhys May 12 '18 at 19:12
  • So add in a `..` or another `os.path.dirname()` call. – Martijn Pieters May 12 '18 at 19:23
  • 1
    `os.path.dirname(os.path.dirname(__file__))` would be `G:/tst`. – Martijn Pieters May 12 '18 at 19:24
  • And, in `b.py`, `__file__` would be `G:/tst/billy/b.py`, so `os.path.dirname(__file__)` would be `G:/tst/billy`. – Martijn Pieters May 12 '18 at 19:25
  • Thanks, that worked! I didn't think of using os.path.dirname() to step back in the hierarchy that way. – Rhys May 12 '18 at 19:46

0 Answers0