I have a Python project with the following directory structure:
project/ project/src/ project/src/somecode.py project/src/mypackage/mymodule.py project/src/resources/ project/src/resources/datafile1.txt
In mymodule.py, I have a class (lets call it “MyClass”) which needs to load datafile1.txt. This sort of works when I do:
open (“../resources/datafile1.txt”)
Assuming the code that creates the MyClass instance created is run from somecode.py.
The gotcha however is that I have unit tests for mymodule.py which are defined in that file, and if I leave the relative pathname as described above, the unittest code blows up as now the code is being run from project/src/mypackage instead of project/src and the relative filepath doesn’t resolve correctly.
Any suggestions for a best practice type approach to resolve this problem? If I move my testcases into project/src that clutters the main source folder with testcases.
in each directory that contains Python scripts, put a Python module that knows the path to the root of the hierarchy. It can define a single global variable with the relative path. Import this module in each script. Python searches the current directory first so it will always use the version of the module in the current directory, which will have the relative path to the root of the current directory. Then use this to find your other files. For example:
If you don’t want to put additional modules in each directory, you could use this approach:
Put a sentinel file in the top level of the directory structure, e.g.
thisisthetop.txt. Have your Python script move up the directory hierarchy until it finds this file. Write all your pathnames relative to that directory.Possibly some file you already have in the project directory can be used for this purpose (e.g. keep moving up until you find a
srcdirectory), or you can name the project directory in such a way to make it apparent.