1

I stored my python file in /home/system/Home/desktop/file.py

import file

ImportError: No module named file

Hossain Muctadir
  • 3,546
  • 1
  • 19
  • 33
Shubham Tiwari
  • 392
  • 1
  • 2
  • 15

1 Answers1

0

If you are using Python 2, then try this

import imp

file = imp.load_source('module.name', '/home/system/Home/desktop/file.py')
file.MyClass()

If you are on 3.4, use this

from importlib.machinery import SourceFileLoader

file = SourceFileLoader("module.name", "/home/system/Home/desktop/file.py").load_module()
file.MyClass()

Else if you use 3.5+, use this:

import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/home/system/Home/desktop/file.py")
file = importlib.util.module_from_spec(spec)
spec.loader.exec_module(file)
file.MyClass()

PS: this solution is adapted from here

Community
  • 1
  • 1
Arwan Khoiruddin
  • 436
  • 3
  • 13