Python import file from variable

Asked

Viewed 517 times

0

If I set 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 from a import foo, me is given Modulenotfounderror: No module named 'a'.

In context, the variable is set to 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 funcor from a import variab

  • Does this solve: https://answall.com/questions/272043/%C3%89-poss%C3%Advel-name-one-m%C3%B3dulo-de-python-using-a-fun%C3%A7%C3%A3o-import/272045#272045

  • I believe it is because the variable is not considered in PYTHONPATH

1 answer

1

Try it here:

import sys
sys.path.append(a)

The modules are searched in this order:

  • Current directory
  • Environment variable PYTHONPATH
  • Default installation address

Use this link as a reference (in English): Python module search path

Edit: After paying attention to your code, I believe from a import foo() nay function, remove the parentheses.

  • All right, but how can I import 'a' after executing these two commands?

  • Like I was doing ;) .

  • I imported sys and defined sys.path.append(a). When trying to import a or import an 'a' element the error was: Module not found. https://imgur.com/a/PituS

Browser other questions tagged

You are not signed in. Login or sign up in order to post.