duude
duude

Reputation: 45

How do I get variables from a different file in a different directory into a python file

So I am trying to get a ton of variables from a file in a different directory WITHOUT just copying and pasting, as thats just cheap, and makes one need to edit ALL the files that use that set of variables.

D:/Tiller OS/garden/memId.py:

mem11 = "D:/Tiller OS/memory/mem1/mem1-1.mem"
mem12 = "D:/Tiller OS/memory/mem1/mem1-2.mem"
mem13 = "D:/Tiller OS/memory/mem1/mem1-3.mem"
mem21 = "D:/Tiller OS/memory/mem2/mem2-1.mem"
mem22 = "D:/Tiller OS/memory/mem2/mem2-2.mem"
mem23 = "D:/Tiller OS/memory/mem2/mem2-3.mem"
mem31 = "D:/Tiller OS/memory/mem3/mem3-1.mem"
mem32 = "D:/Tiller OS/memory/mem3/mem3-2.mem"
mem33 = "D:/Tiller OS/memory/mem3/mem3-3.mem"
memro1 = "D:/Tiller OS/memory/romem/memro-1.mem"
memro2 = "D:/Tiller OS/memory/romem/memro-2.mem"
memro3 = "D:/Tiller OS/memory/romem/memro-3.mem"

How do I get all this info into a file at D:/Tiller OS/programs/prog.py?

Upvotes: 1

Views: 867

Answers (1)

Nathan
Nathan

Reputation: 10306

If D:/Tiller OS/garden/ is on your path, you can just do from memId import mem11, etc. It doesn't matter whether something is a function, class, or other object when importing in Python.

However, if all that memId.py contains is a list of these variables, I agree with @melpomene that you it might be better to use a different format to store these. You could use, for example, a TOML file. The format you have above is already valid TOML, so you'd just rename it to memId.toml and then in prog.py you could do something like

import toml
mem_path = "D:/Tiller OS/garden/memId.toml"
mems = toml.load(mem_path)

mems would then be a dictionary and you could access mem11 as mems["mem11"] and similarly for the others. toml is not in the standard library, so you would need to pip install toml if you don't have it. You could just use a JSON file instead if you don't want that; json is in the standard library. However, I think TOML is nicer than JSON, and JSON would require changing the format of your file.

Upvotes: 2

Related Questions