Search code examples
pythonexternal

Is there a function to import external file to main file?


import sys
import os


module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
    sys.path.append(module_path+"E:\\myfolder")

import myfile

Error:

[ModuleNotFoundError: No module named 'myfile']

Solution

  • I think you're wrong at the sys.path.append(module_path+"E:\\myfolder") statement. Because the module path is now the absolute path, You don't need E: prefix.

    Try again with:

    sys.path.append(module_path+"\\myfolder")
    

    You can check your paths by print(sys.path). It will print all paths that it's looking for the module