0

I've succeeding in importing a single file, but the file calls other files and I get an error. So I'm trying to import and entire folder. I would prefer not to import each file one by one since I know it must be possible to import the whole folder. Here is the syntax I used to import a file:

import importlib.machinery
import os


temp_directory2 = '/Users/me/PycharmProjects/inference_engine2/inference2/ancient/temp.py'
temp_directory = '/Users/me/PycharmProjects/inference_engine2/inference2/Proofs/main_loop.py'
main_directory = '/Users/me/PycharmProjects/inference_engine2/inference2/Proofs/'


b = os.path.exists(temp_directory)
loader = importlib.machinery.SourceFileLoader('temp', temp_directory)
handle = loader.load_module('temp')
fred russell
  • 307
  • 2
  • 11
  • *"but the file calls other files and I get an error"* – how does that file "call other files"?! Each module should declare and import its own dependencies, it shouldn't depend on some other module loading its dependencies. – deceze Jan 24 '18 at 16:26

2 Answers2

1

Convert it to a package using __init__.py. more here : https://docs.python.org/2/tutorial/modules.html

cdarke
  • 42,728
  • 8
  • 80
  • 84
1

You can add the path to the list sys.path at the beginning of your file, like so:

import sys; sys.path.insert(0, r'C:/Users/me/PycharmProjects/inference_engine2/inference2/Proofs')

Note since you are inserting the path at the beginning of the list, this is the first place python will go to look for a module.

jpp
  • 159,742
  • 34
  • 281
  • 339