Python Forum

Full Version: Importing modules issue
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I have a python file called ImportingModules.py

I have saved this file purposely on my desktop because I want to see how you can add an Environmental Variable called PYTHONPATH and set this equal to the path where ImportingModules.py is saved (The path is C:\Users\mp88_\OneDrive\Desktop). Then I want to import this file in another module.

When i try doing this using this one line code:

import ImportingModules.py
I get an error saying "No module named ImportingModules"

I am using Windows 10 Home and executing the code using Visual Studio 2019.

Why am I getting this error?

Thank You
Does it really say "No module named ImportingModules" or "No module named ImportingModules.py"? You don't want to put the ".py" on the import line.
import ImportingModules
Hi,

Sorry, I removed the ".py" from "import ImportingModules.py" so it now reads "import ImportingModules".

Still get an error saying "No module named ImportingModules"

I've also added __init__.py file in the directory where I am trying to import from as some threads have suggested that.

But still no luck
Your procedure sounds correct, and works fine for me on my linux box. I won't be able to validate it on Windows for a while. How did you set PYTHONPATH?

You don't need an __init_.py. You can import bare modules without it.
I set up my PYTHONPATH variable as follows:

1). Goto my pc
2). Properties
3). Advanced System settings
4). Then click on Environment Variables
5). Then click on New under "User Variables for mp88_". There is also System variables too but I added it under User Variables.
6). PYTHONPATH = C:\Users\mp88_\OneDrive\Desktop
Have you restarted your PC since adding the PYTHONPATH?
Yes, I have restarted my pc since adding PYTHONPATH
Restart as mention.
Then start python repl from command line,to test that it work.
C:\
λ python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 21:26:53) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>>
>>> os.environ['PYTHONPATH']
'C:\\bar'
Here i have set PYTHONPATH to C:\bar as a test.

Look at this post for an other way not using PYTHONPATH.
in command prompt, os.environ['PYTHONPATH'] prints 'C:\\Users\\mp88_\\OneDrive\\Desktop'
Check that path and file is really working from cmd,you know how to navigate and look at files from cmd cd and dir?
Example with more to open a file on Desktop.
C:\>more C:\Users\Tom\Desktop\intro.py
print('hello world')
cmd/Powershell is terrible as i use cmder,had to search for how to open a file more as i had forget it,
in cmder is like a normal way with cat Wink
C:\
λ cat C:\Users\Tom\Desktop\intro.py
print('hello world')
Desktop is not good folder for storing files,make folder with simpler path like eg C:\code