21

I'm writing an installation program that will pull a script out of an existing Python file and then use it in the main Python program. What I need to know how to do is import <file> from the current working directory, not the standard library or the directory the main code is in. How can I do that?

Nathan2055
  • 2,283
  • 9
  • 30
  • 49
  • This questions seems to have already been answered: [enter link description here][1] [1]: http://stackoverflow.com/questions/1112618/import-python-package-from-local-directory-into-interpreter – rhinoinrepose Apr 15 '13 at 17:25
  • @rhinoinrepose - No, that looks like someone who is having an issue using the code discussed below. Doesn't seem like a dupe to me. – Nathan2055 Apr 15 '13 at 17:40
  • @Nathan2055: All the answers below are essentially answers to the question linked to by rhinoinrepose. If these answers work for you, your question is a duplicate. If these answers do not work for you, you need to give more information. – John Y Apr 15 '13 at 17:48
  • 2
    @JohnY & @rhinoinrepose: I don't agree. First of all, the answers are for Python 2.5, I am using Python 3.3. Secondly, the answers assume you already know about `sys.path.append`, which I did not, being a Python noob. – Nathan2055 Apr 15 '13 at 18:40

3 Answers3

36

This works:

import os
import sys
sys.path.append(os.getcwd())
import foo
Evgenia Karunus
  • 10,715
  • 5
  • 56
  • 70
Tyler Eaves
  • 12,879
  • 1
  • 32
  • 39
17
import sys
sys.path.append('path/to/your/file')
import your.lib

This will import the contents of your file from the newly appended directory. Appending new directories to the Python Path in this way only lasts while the script is running, it is not permanent.

woemler
  • 7,089
  • 7
  • 48
  • 67
7

You should be able to import the module from your current working directory straight away. If not, you can add your current working directory to sys.path:

import sys
sys.path.insert(0, 'path_to_your_module') # or: sys.path.insert(0, os.getcwd())
import your_module

You can also add the directory to PYTHONPATH environment variable.

piokuc
  • 25,594
  • 11
  • 72
  • 102