How to import other Python files?

PythonServer Side ProgrammingProgramming

To use any package in your code, you must first make it accessible. You have to import it. You can't use anything in Python before it is defined. Some things are built in, for example the basic types (like int, float, etc) can be used whenever you want. But most things you will want to do will need a little more than that. For example, if you want to calculate cosine of 1 radian, if you run math.cos(0), you'll get a NameError as math is not defined.


You need to tell python to first import that module in your code so that you can use it.

>>> math.cos(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'math' is not defined
>>> import math
>>> math.cos(0)

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, in the current directory.
                   # For files in other directories, provide path to that file, absolute or relative.
Updated on 13-Dec-2019 10:37:17