1

In Python (2.7), I'd like to create several variables in a file. Then use those variables in other files. There aren't any classes or function. Just accessing those variables from different files.

How is that done for the file containing variables, which might look like this?

variables.py

a = 1
b = 2
c = 3

Then in a file that wants to use those variables?

file1.py

print a + b
mtt2p
  • 1,818
  • 1
  • 15
  • 22
4thSpace
  • 43,672
  • 97
  • 296
  • 475

4 Answers4

6

Another way is to import file than use filename to access variables:

import variables

print variables.a + variables.b
metmirr
  • 4,234
  • 2
  • 21
  • 34
4

If those are in proper python format i.e. the way you have mentioned above

In your file1.py You can just do this.

from variables import *

print a + b
Bipul Jain
  • 4,523
  • 3
  • 23
  • 26
1

You can use import to import your work from that file to the next, like so:

from variables import *

print a + b

If you're still confused, refer to this post here which will give you an in-depth explanation: Python: How to import other Python files

Community
  • 1
  • 1
0

It is exactly as people told above

Importing variables from another file?

Here it will have more information about how to do it with methods and scripts. This also aplies to your problem

Community
  • 1
  • 1
Breno Baiardi
  • 99
  • 1
  • 16