2

I have a directory structure like -

  • D
    • dir1
      • filetoimport.py
    • dir2
      • filetoimport.py
      • run.py

Filetoimport.py code-

call_function()
    do_something
    return

Run.py has -

import filetoimport
filetoimport.call_function()

the dir2 is essentially a copy of dir1 with some changes but run.py is still calling filetoimport from dir1. I don't get what am I missing here?

EDIT 1- dir1 and dir2 are not packages but just plain directories.

7
  • And you added the local __init__.py? Commented Oct 25, 2019 at 10:35
  • It is not recommanded to call modules with the same name. Have you put an __init__. py file in each package? Finaly you should call it from the root. from dir2 import filetoimport Commented Oct 25, 2019 at 10:35
  • Use correct folder structure and make sure you're in correct working directory! | As for colliding names, with correct folder structure you can do from package.module import needed_function, or import package.module (qualified name with package name), or import package.module as different_name (you can do as on single functions with colliding names as well!) Commented Oct 25, 2019 at 10:44
  • @FlorianBernard getting no module named dir2 error Commented Oct 25, 2019 at 10:55
  • @user2828360 from D.dir2 import filetoimport. And you should have init file in each directory. Commented Oct 25, 2019 at 10:56

1 Answer 1

2

I suppose you are running your code from dir1 as the working directory (you can check with os.get_cwd()). Change your working directory to dir2 and it should import the filetoimport.py under dir2.

If you want to be sure what was imported you can print(fileimport.__file__)

Sign up to request clarification or add additional context in comments.

3 Comments

It doesnt seem to work. print(os.getcwd()) shows the correct directory
your working directory is dir2? what fileimport.__file__ shows? Are u running it from simple shell or from ide?
if you print sys.path, do you see dir1 there? did you set the PYTHONPATH environment variable?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.