How to Import a File in Python

To import a file in Python, you can use the ‘import’ keyword followed by the name of the module file (without mentioning the file extension). For instance, if your module file is named, you only import my_module.

“import” syntax

import modulename


Create a new file called and add the following code inside the file.

def add(a, b):
  c = a + b
  return c

The file has one function called add(), which takes two parameters and returns the sum of the provided arguments.

The file is a module in the above file, and add() is its method.

We can import the sum module using the “import sum” inside the other file. But first, let’s import the file, which is in the same directory as the file.


import sum

So, the import syntax is the following.

In our example, modulename = sum.

Now, we can use the add() function of the sum module.


import sum

print(sum.add(3, 4))



If you intend to use the add() function more than once in your file, you can assign it to a local name.


import sum

summation = sum.add
print(summation(3, 4))



Importing Specific Functions or Variables

In Python, you can import specific functions, classes, or variables from a module rather than the whole module. This can make your code more concise and clear about what is being used from the external module.

Here’s how you can do this:

Importing Specific Functions

If you have a module named with the following content:

def my_function():
  print("This is my function!")

def another_function():
  print("This is another function!")

You can import only my_function from this module in another file like this:

from mymodule import my_function


Importing Specific Variables

Similarly, if you have some variables in the module:


another_variable = "Hello, World!"

You can import a specific variable:

from mymodule import CONSTANT_VALUE


Importing with an Alias

You can also use aliases if there are naming conflicts or if you want to shorten a long name:

from mymodule import my_function as mf


That’s it.

Related posts

How to import a class from another file

Python cannot import name: How to Solve ImportError

Python Unresolved Import: How to Solve Pylint Error

2 thoughts on “How to Import a File in Python”

  1. I must remove “-” and “_” from the name of the file to import; from “” to “” in order that can be imported.

    from math import factorial
    def Comb(n, k):
    c = factorial(n)/(factorial(n – k)*factorial(k))
    a = int(input(“Dame valor grande = “))
    b = int(input(“Dame valor chico = “))
    y = CoefBinomiales23.Comb(a, b)
    print(“La combinación combinada es = “, y)

    Only when I remove – and _ from the names the importation can be done, despite they are allowed in varible names.


Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.