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.
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.
## 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
"""" Good demonstration by showing that a module can find files placed next to it by using the module file location. That approach works for simple scripts and local testing, but a couple of caveats are important: __file__ is optional (some loaders or frozen builds omit it) and binding an open file's .read method at import time can leave file handles open or be brittle. (docs.python.org)
For robust, forward-compatible access to package data prefer the stdlib package-resource APIs (they work for normal installs, wheels, zipimport, etc.). Example (modern Python):
import importlib.resources as resources
cfg_text = resources.read_text('mypackage', 'mycfg.cfg', encoding='utf-8')
This reads the resource text regardless of whether the package lives on the filesystem or inside an archive. (docs.python.org)
If a real filesystem path is required (for subprocesses or native libraries), use importlib.resources.path(...) as a context manager or compute an absolute module directory with pathlib.Path(__file__).resolve().parent while handling the case that __file__ might be missing. For older Python releases use the importlib_resources backport or pkgutil.get_data as fallbacks. Prefer reading via these resource helpers or with a with open(...): block rather than leaving open file objects at module import. (docs.python.org)
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.