Skip to content Skip to sidebar Skip to footer

Import Own .py Files In Anaconda Spyder

I've written my own mail.py module in spider (anaconda). I want to import this py file in other python (spider) files just by 'import mail' I searched on the internet and couldn't

Solution 1:

To import any python script, it should exist in the PYTHONPATH. You can check this with the following code:

import sys
print sys.path

To import your Python script:

  1. Put both the scripts (main and the imported python script) in the same directory.
  2. Add the location of the file to be imported to the sys.path.

For example, if the script is located as '/location/to/file/script.py':

 import sys
 sys.path.append('/location/to/file/')
 import script

Solution 2:

I had the same problem, my files were in same folder, yet it was throwing an error while importing the "to_be_imported_file.py".

I had to run the "to_be_imported_file.py" seperately before importing it to another file.

I hope it works for you too.


Solution 3:

Searched for an answer for this question to. To use a .py file as a import module from your main folder, you need to place both files in one folder or append a path to the location. If you storage both files in one folder, then check the working directory in the upper right corner of the spyder interface. Because of the wrong working directory you will see a ModuleNotFoundError.


Solution 4:

There are many options, e.g.

  • Place the mail.py file alongside the other python files (this works because the current working dir is on the PYTHONPATH.
  • Save a copy of mail.py in the anaconda python environment's "/lib/site-packages" folder so it will be available for any python script using that environment.

Solution 5:

I did a slightly different solution approach that is less sophisticated. When I start my anaconda terminal it is at a C prompt. I just did a cd d:\mypython\lib in the beginning window before starting python. once I did that I could simply just import my own classes that I put in that library with "import MyClass as my" then I was off and running. It is interesting, I did 2 days of internet searching in my part time and could not find the answer either, until I asked a friend.

cd d:\mypython\lib
python
>>> import MyClass as my
>>> my1=my.MyClass()
>>> my1.doSomething() 

worked for me on my anaconda / windows 10 environment python 3.6.6.


Post a Comment for "Import Own .py Files In Anaconda Spyder"