Python Forum

Full Version: How do I read variables from another python file?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello!

I am new to this forum so I hope I am posting in the right place.

I have a python program that creates another python file and declares 4 variables in it. How can I read the variables from the other file? Here is the first file "CodeTest.py":

import random

testFile = open("testFile.py", "w+")

testString = "abcd"

for i in range(len(testString)):
    testRandom = random.randint(2048, 4096)
    testFile.write(str(testString[i] + " = " + str(testRandom) + "\n"))

print("Variables declared in file testFile.py")
and this is the file created "testFile.py":

a = 2316
b = 2498
c = 3607
d = 3290
But now what do I add to CodeTest.py to be able to read the values in testFile.py?

Thanks
You can do
namespace = {}
with open("testFile.py") as ifh:
    contents = ifh.read()
exec(contents, namespace)
print(namespace['a'], namespace['b'])
It would be better to put those values in a dictionary. Also, you are iterating over the indexes of a string. It is better to iterate over the string itself:

import random
 
testString = "abcd"
 
data = {}
for char in testString:
    data[char] = random.randint(2048, 4096)
You can now access the random numbers with data['a'], data['b'], and so on.
Thanks!
#ichabod801
Also a tip if you want to save dictionary from @ichabod801 code.
You can use JSON.
import random
import json

testString = "abcd"

data = {}
for char in testString:
    data[char] = random.randint(2048, 4096)

with open("test_file.json", "w") as j_out:
    json.dump(data, j_out)
Now can read that JSON file from a other file.
import json

with open("test_file.json") as j:
    data = json.load(j)
Test:
>>> data
{'a': 3183, 'b': 2707, 'c': 2581, 'd': 2144}
>>> data.get('c', 'Not in record')
2581
>>> data.get('d', 'Not in record')
2144
>>> data.get('e', 'Not in record')
'Not in record'
Can also look at configparser.
Then have on disk a .ini file.
[DATA]
a = 3183
b = 2707
c = 2581
d = 2144
Make:
import configparser

testString = "abcd"

data = {}
for char in testString:
    data[char] = random.randint(2048, 4096)

config = configparser.ConfigParser()
config['DATA'] = data

with open('example.ini', 'w') as configfile:
    config.write(configfile)
Read:
import configparser

config = configparser.ConfigParser()
config.sections()
config.read('example.ini')
Test:
>>> config['DATA']['c']
'2581'
>>> config['DATA']['d']
'2144'
>>> config['DATA'].get('e', 'Not in record')
'Not in record'
Thanks @snippsat