Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use import statement for custom modules in Python

Tags:

python-3.x

I am very new to python programming and writing simple helloworld program by using python 3.3 on windows environoment.The helloworld program is saved as hello.py. So how can i use it in another module. I tried sys.path.append and give path of my save file but its not working. Can somebody tell me do i have to set Environment variable in windows xp

Thanks.

like image 468
user2696156 Avatar asked Aug 28 '13 10:08

user2696156


People also ask

How do you import modules in Python?

Importing Modules To make use of the functions in a module, you'll need to import the module with an import statement. An import statement is made up of the import keyword along with the name of the module. In a Python file, this will be declared at the top of the code, under any shebang lines or general comments.

What is import statement in modules in Python?

Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way. import module_name.

How do I import a custom file into Python?

If you have your own python files you want to import, you can use the import statement as follows: >>> import my_file # assuming you have the file, my_file.py in the current directory. # For files in other directories, provide path to that file, absolute or relative.


2 Answers

Use this way:

import sys

then:

sys.path.insert(0,"X")

Where X is the directory you want to import from.

After that you just need to import your custom module:

import X

Thats all.

like image 70
Odai Al-Ghamdi Avatar answered Sep 30 '22 19:09

Odai Al-Ghamdi


There is a directory DIR containing our module X: /DIR/X

import sys    
sys.path.insert(0,"DIR")
import X

This imports the module e.g. X =hello.

like image 24
Mateusz Avatar answered Sep 30 '22 21:09

Mateusz