Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 find a clearly solution.

like image 973
user5488652 Avatar asked Oct 29 '15 08:10

user5488652


People also ask

How do I import a .py file into Spyder?

To import your Python script: Put both the scripts (main and the imported python script) in the same directory. Add the location of the file to be imported to the sys. path.

Can we import a .py file?

If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory. # For files in other directories, provide path to that file, absolute or relative.

How do I make Spyder default for .py files?

When you get the Open With... dialog, select the "Select a program from a list of installed programs" option. Then make sure the "Always use the selected program to open this kind of file" option is selected. Click "Browse" to point to the Spyder executable.


3 Answers

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
like image 148
Sahil M Avatar answered Oct 03 '22 14:10

Sahil M


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.

like image 33
Bamwani Avatar answered Oct 03 '22 13:10

Bamwani


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.

like image 41
Leopold Gerber Avatar answered Oct 03 '22 13:10

Leopold Gerber