0

I have a piece of code located in a file (utils.py) in a folder different from the one my current script is located in. I tried:

from "/Z/scripts/utils.py" import *

but it gives a syntax error. Is there a way to "include" my own code located elsewhere other than the current folder?

Old Geezer
  • 14,854
  • 31
  • 111
  • 198
  • possible duplicate of [Import a module from a relative path](http://stackoverflow.com/questions/279237/import-a-module-from-a-relative-path) – umut Nov 19 '14 at 06:32
  • 1
    if scripts folder has `__init__.py` file then you can use `from Z.scripts.utils import *` – Ashwani Nov 19 '14 at 06:37
  • @AshwaniDausodia Thanks. `/` becomes `.`? What happens if the path name contains periods? – Old Geezer Nov 19 '14 at 06:44

2 Answers2

1

You need to add that directory to your python path

import sys
sys.path.append("/Z/")
from scripts.utils import *

Make sure the scripts directory contains an __init__.py file

John Jiang
  • 11,069
  • 12
  • 51
  • 60
  • 1
    This assumes there is a `__init__.py` in /Z/scripts , which may not be the case. Why wouldn't you recommend `sys.path.append("/Z/scripts"); from utils import *`? – SethMMorton Nov 19 '14 at 06:35
0

You can import code that is in a directory if it is added to PYTHONPATH. See here for more details.

Community
  • 1
  • 1
101
  • 8,514
  • 6
  • 43
  • 69