1
Folder A:
   Script A:
   Folder B:
     Script B(attempting to import Script A)

I am trying to import Script A into Script B (which is in a subfolder called Folder B)

When running this piece of code:

from Folder A import Script A

I get the following error:

No module named Script A
user12625679
  • 676
  • 8
  • 23

2 Answers2

1

Put an __init__.py file in Folder A.

Make sure Folder A is in your PYTHONPATH environment variable.

Then it should work.

TheEagle
  • 5,808
  • 3
  • 11
  • 39
  • Do I need if __name__ == '__main__': main() in Script B then? – – user12625679 Nov 29 '21 at 15:19
  • @user12625679 no you don't need it - you can directly call `main()`, but normally that is put in to only run the `main` function if the script is not imported but run directly. – TheEagle Nov 29 '21 at 17:54
1

After including __init__.py in parent directory (folder A). You should be able to do "import Script A"

Munchies
  • 19
  • 3
  • Do I need ```if __name__ == '__main__': main() ``` in Script B then? – user12625679 Nov 29 '21 at 15:18
  • Only if you want a main method? the if __name__ == '__main__' is effectively a starting point for your code, like a main method in java. Otherwise you can just run main function directly like main(). It's good for readability as it helps other people know where your code entry point is. I'd suggest you use it, but you don't have to. – Munchies Nov 29 '21 at 16:24