Amy D
Amy D

Reputation: 581

Importing Self Written Python Module

I've read through many of the other S-O questions relating to this, but still am having trouble getting it to work for me. Apologies in advance for the overlap! I'm using python 2.7.10, on Windows 7.

I'm trying to import a module that I wrote, in my Python Console in PyCharm (doubt that matters). In the console, I navigate until I'm in the directory that contains my module:

/users/usn/.../Tools/my_file.py

which can be confirmed using pwd. I then try

import my_file

but get the error ImportError: No module named my_file. I tried a number of variations to no avail. How can I import the module I wrote, in the console?

Thanks

Upvotes: 3

Views: 24181

Answers (5)

questionto42
questionto42

Reputation: 9630

You can also take the relative path that you can get for example in codium/vscode when right-clicking on the file or check it out yourself.

You can then directly import with

import relative.path.to.my_file.py
from relative.path.to.my_file.py import my_function

or in the example, likely like:

import some_folder.Tools.my_file.py

Upvotes: 0

onouv
onouv

Reputation: 610

I believe, one can also use site :

import site
site.addsitedir('/users/usn/.../Tools/')
import my_module

However, why they didn't allow for an import statement to just reference a relative path like in JavaScript escapes me ...

Upvotes: 0

Miladiouss
Miladiouss

Reputation: 4720

To import your module, you need to add its directory to the environment variable, either temporarily or permanently.

Temporarily

import sys
sys.path.append("/path/to/my/modules/")
import my_module

Permanently

Adding the following line to your .bashrc file (in linux) and excecute source ~/.bashrc in the terminal:

export PYTHONPATH="${PYTHONPATH}:/path/to/my/modules/"

Credit/Source: saarrrr, another stackexchange question

Upvotes: 4

Abc Xyz
Abc Xyz

Reputation: 1434

You can also use imp

import imp
my_file = imp.load_source('name', '/users/usn/.../Tools/my_file.py')

Load and initialize a module implemented as a Python source file and return its module object. If the module was already initialized, it will be initialized again. The name argument is used to create or access a module object. The pathname argument points to the source file. The file argument is the source file, open for reading as text, from the beginning.

Upvotes: 4

saarrrr
saarrrr

Reputation: 2897

You need to extend your environment to the folder where the module is located. Add this to the top of your file into which you are importing your module.

import sys
sys.path.append("/users/usn/.../Tools/")
import my_file

Upvotes: 10

Related Questions