There are a couple of possibilities, depending on your precise requirements.
Firstly some basic terminology:
is a python (*.py) file that is on the python path. (It can be other sorts of files such as .pyd, but we will ignore that for now).
is a directory on the python path that has an __init__.py file in it. Modules can live in packages, and packages can be nested.
I will assume that in your example F1 and F2 are modules and D1 and D2 are packages.
If you know the package/module structure (e.g. D2.F2) then you can get the directory from the package's __path__ attribute:
# this is module F2 in package D2
here = D2.__path__
f = open( os.path.join(here, 'filename'))
# do stuff with f
I use this a lot in my unit test code when I need to read a file of test data.
If you have only an object to work with then it becomes more tricky, but still possible.
You can get the class of an object through it's __class__ attribute, and you can get the module that the class was defined in from the classes __module__ attribute. This gives you a string representation of the module, e.g. "package.path", so you need to convert that to an absolute directory path. There are a couple of ways of doing this, but the simplest is to look it up in the sys.modules dictionary, which will return the actual module object, and the module's __file__ attribute give you the path of the module file. Whew!
So here is a function that will take almost any object and return the directory its class was defined in:
import sys, os
 almost any, since it will fail for things like builtin classes which do not have an associated file.
Dave - The Developers' Coach