Getting access to modules directory name to load files relative to that UserPageVisits:528 active 80 80 DaniWeb 561 60 2010-06-23T02:50:45+00:00 https://www.daniweb.com/programming/software-development/code/291899/getting-access-to-modules-directory-name-to-load-files-relative-to-that

Getting access to modules directory name to load files relative to that

TrustyTony

I made this program during forum discussion for accessing configuration relative to module directory, not main program's position (which can be accessed by sys.argv[0]'s directoryname).

As the thread is closed I post my proves as code snippet.

528 Views
About the Author

IT Pro doing Eng-Fin-Eng translations

code snippet
## file one: main.py, main program in your working directory
# this code must run directly, not inside IDLE to get right directory name
import os, mytest
curdir=os.path.dirname(__file__) 
print '-'*10,'program','-'*10
print 'Program in',curdir
print 'Module is in', mytest.curdir
print 'Config contents in module directory:\n',mytest.config()
input('Push Enter')

## file two: mytest.py, module somewhere in PATH or PYTHONPATH
import os
curdir= os.path.dirname(__file__)

print "Test module directory is "+curdir

## function, not call to function
config=open(os.path.join(curdir,'mycfg.cfg')).read
""" Example output:
Test module directory is D:\Python Projects
---------- program ----------
Program in D:\test
Module is in D:\Python Projects
Config contents in module directory:
[SECTIONTITLE]
SETTING=12

Push Enter
""""