[英]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
: 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
? 如何将所有这些信息保存到
D:/Tiller OS/programs/prog.py
?
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. 如果
D:/Tiller OS/garden/
在您的路径上,则可以from memId import mem11
等执行操作。在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. 但是,如果
memId.py
包含的只是这些变量的列表,我同意@melpomene的话,最好使用其他格式存储这些变量。 You could use, for example, a TOML file. 您可以使用例如TOML文件。 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 您上面的格式已经是有效的TOML,因此您只需将其重命名为
memId.toml
,然后在prog.py
可以执行以下操作
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. 然后,
mems
将成为字典,您可以将mem11
作为mems["mem11"]
来访问,其他类似。 toml
is not in the standard library, so you would need to pip install toml
if you don't have it. toml
不在标准库中,因此如果没有pip install toml
则需要pip install toml
。 You could just use a JSON file instead if you don't want that; 如果您不想这样做,可以只使用JSON文件。
json
is in the standard library. json
在标准库中。 However, I think TOML is nicer than JSON, and JSON would require changing the format of your file. 但是,我认为TOML比JSON更好,并且JSON需要更改文件的格式。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.