Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import a file from different directory

i'm using python 2.7. I have written a script, i need to import a function from some other file which is there in different folder. my script is in the path

C:\python\xyz\xls.py

Path of File having function that i need to call is

C:\python\abc.py

i tried like this

from python.abc import *

but it is not working. Is there any other way to call the function or i need to move the files into same directory? Please help Thank you

like image 907
user19911303 Avatar asked Nov 29 '12 08:11

user19911303


2 Answers

You can dynamically load a module from a file:

import imp
modl = imp.load_source('modulename', '/path/to/module.py')

The imp module docs will give you more details.

like image 172
Martin Maillard Avatar answered Sep 21 '22 16:09

Martin Maillard


You cat set the PYTHONPATH environment variable:

c:\> set PYTHONPATH=c:\python

And then, normally:

from abc import *

Alternatively, if you don't want or can't change the environment, you can change the path at runtime:

import sys
sys.path.append(r'c:\Python')
from abc import *
like image 35
rodrigo Avatar answered Sep 24 '22 16:09

rodrigo