Skip to content

Python import variable from another file | Example code

  • by

First import the file from the current program, then you can import the variable or access the variable in Python. There are three approaches to importing variables from another file.

  • import <file> and then use <file_name>.<variable_name> to access variable
  • from <file> import <variable_names> and use variables
  • from <file> import * and then use variables directly.

Example import variable from another file in Python

Simple example code.

file_name.variable_name to access variable

Simple import and print the value of a variable.

main.py

var = "Hello main file"

Test.py

import main

print(main.var)

Output: Hello main file

Python import variable from another file

From file import variable and use variables

Access the variables by just their name.

main.py

var = "Hello main file"

Test.py

from main import var

print(var)

Output:

from import * and then use variables directly.

Use the following header, It will import all objects and methods into a file.

main.py

from main import *

print(var)
print(num)

Test.py

var = "Hello main file"
num = 10

Output:

from import and then use variables directly

Do comment if you have any doubts or suggestions on this Python variable tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *