pnkjmndhl
pnkjmndhl

Reputation: 585

Run Python codes on subdirectories

How do I run python codes (.py) on subdirectories from the main folder?

What is the easiest way to do this?

I tried:

os.chdir("path") #path = path to subdirectory 
import abc #abc = module on subdirectory

Error:

ImportError: No module named abc

Upvotes: 0

Views: 46

Answers (3)

Alvaro Valle
Alvaro Valle

Reputation: 92

well, just do it

import sys
sys.path
sys.path.append('/path/to/the/example_file1.py')
sys.path.append('/path/to/the/example_file2.py')
sys.path.append('/path/to/the/example_file3.py')
import example_file1
import example_file2
import example_file3

Upvotes: 0

cs95
cs95

Reputation: 402333

I believe you want to import abc into your current module, even though they're located on different folders. Depending on your python, there are different ways to do this:

Python2.x

import imp
abc = imp.load_source('abc', '/path/to/abc.py')

Python 3.4

from importlib.machinery import SourceFileLoader
abc = SourceFileLoader('abc', '/path/to/abc.py').load_module()

In either case, abc will be imported for use as usual.

>>> abc
<module 'abc' from '/path/to/abc.py'> 

This is cleaner because it does not involve polluting your sys.path.

Upvotes: 1

Alvaro Valle
Alvaro Valle

Reputation: 92

Take a look at this

import sys
sys.path
sys.path.append('/path/to/the/example_file.py')
import example_file

Upvotes: 0

Related Questions