tags:

views:

83

answers:

2

Hey , I have a newbie question about importing in Python

First : How exactly can I import a specific python file .. import file.py sometimes doesn't work
Second : How to import a folder .. instead of a specific file

Third ( and the most important ) : I want to load a Python file dynamically in runtime, based on user input

Thanks

+6  A: 

First: No doubt import file.py didn't work because you shouldn't add the the extension '.py' Just use this import file

Second: Create an empty file under your desired folder named __init__.py yes, Empty file , no coding is required here later you may see another file in same folder named __init__.pyc , just leave it and don't delete it

Third: There is a pretty nice function called __import__() it takes string (the name of the module (AGAIN:WITHOUT .PY)

pmName = input('Enter file name : folder/___.py ')
pm = __import__(pmName)
print(dir(pm)) # just for fun :)

try help(__import__()) in your interpreter for advanced usage

That all folks

Radian
thank you very much for you fast responseyes.. it workssssThank you again
Tamer
+1  A: 

first of all: you can only import from the pythonpath - i suggest you google for it - this will become very important for you :-)

you do not import filenames in python you import modules

if your code is in a file called file.py try this:

from file import my_functionname

renton