Python import variable from another file | Example code

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 import 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 and suggestions on this Python variable tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

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