Alex
Alex

Reputation: 44265

How to test if a directory is a python module path?

In order to test if a directory path if a python module path (i.e. contains a file named __init__.py) one can do something like

os.path.isfile(os.path.join(path, '__init__.py'))

I wonder if there is a special function call to do that?

Upvotes: 0

Views: 93

Answers (1)

Abhijit
Abhijit

Reputation: 63707

You can use the imp.find_module(name[, path]) to test if a particular module is present in a certain path

How to use

import imp
fname, pathname, description = imp.find_module("__test__.py", path)
if not fname:
    #File is not present
else:
    #File is present
    fname.close()

Form the documentation

If search is successful, the return value is a 3-element tuple (file, pathname, description): ..... If the module does not live in a file, the returned file is None, pathname is the empty string, and the description tuple contains empty strings for its suffix and mode

Upvotes: 2

Related Questions