Python import file from variable

0

If I define a variable as the directory from which I will import a file, such as:

a = 'C:\Users\Windows 7\Desktop\Program10.py

If I try to from a import foo , I'm given ModuleNotFoundError: No module named 'a'.

In context, the variable is defined as a directory in this loop:

d_user = getpass.getuser()
diret = "C:\Users\" + d_user
for root, dirs, files in os.walk(diret):
    if lookfor in files:
        a = join(root, lookfor)
        break

And what I want to do is from a import func or from a import variab

    
asked by anonymous 12.04.2018 / 14:09

1 answer

2

Try this here:

import sys
sys.path.append(a)

Modules are searched in this order:

  • Current Directory
  • Environment variable PYTHONPATH
  • Default installation address

Use this link as a reference: Module search path in Python

Edit: After paying attention to your code, I believe% wont work , it will remove the parentheses.

    
12.04.2018 / 15:07