-1

A very basic question that has been confusing me. Can't seem to find any solutions online so far...

I have a simple script and want to import another script I just made in the same directory.

What is the proper way of doing this?

I just tried combos of import myfile, from myfolder import myfile, import myfolder.myfile, etc

I get ImportError: No module named 'myfile'

Cheers

darkace
  • 838
  • 1
  • 15
  • 27

1 Answers1

0

This is because your current directory isn't on the PYTHON_PATH, which is what import searches when you call it. See the documentation.

If you want an immediate fix, you can use the following:

import sys, os
sys.path.append(os.path.abspath(os.path.dirname(__file__)))

This adds the directory containing the script's file to the python path.

This will only work if the directory these scripts are in is set up as a package.

aruisdante
  • 8,875
  • 2
  • 30
  • 37
  • Ok, so there's no simpler way of doing it? – darkace Mar 08 '14 at 21:14
  • also, does that permanently add the directory to the python_path? – darkace Mar 08 '14 at 21:16
  • 1
    It adds the directory to the path for the scope of the import (so the lifetime of the script in this case). `sys.path` is a copy of the environment variable, not the actual environment variable, so that you can do things exactly like this. And no, that's how the `import` command works. The package containing the module must be on `PYTHON_PATH`. – aruisdante Mar 08 '14 at 21:21
  • Ok, that makes sense. Now I might be being a total noob but it's not recognising < __file__> – darkace Mar 08 '14 at 21:28
  • Oh is this because I'm running the script through an editor instead of a command line – darkace Mar 08 '14 at 21:40
  • 1
    Depending on how you're hitting that line, `__file__` may or may not exist (for example if you run the module from the interactive interpreter). – aruisdante Mar 08 '14 at 21:43
  • Only just saw you're comment but that's right. Just got it working through a terminal (after cleaning up some env variables). Do you know the right approach to doing this through an interactive interpreter? – darkace Mar 08 '14 at 21:58
  • silly question, just put the directory in manually. – darkace Mar 08 '14 at 22:00
  • although that doesn't seem to work. In any case, problem is solved :) – darkace Mar 08 '14 at 22:18
  • You could try `sys.path.append(os.path.abspath(''))`, should also give you the directory in the interactive case, **assuming** you launched python from that directory. It won't work in any other case though. – aruisdante Mar 08 '14 at 22:20