我有一个共享文件夹,其中包含一个文本文件,我希望我的程序像引用 .py 文件一样引用该文件。例如,我的 .txt 文件中有一个我在程序中引用的字典。如何从文本文件导入词典?我是逐行阅读吗?或者有没有办法让 python 认为它是一个 .py 文件。
这是一个类似于我的 .txt 文件的示例:
#There are some comments here and there
#lists of lists
equipment = [['equip1','hw','1122','3344'],['equip2','hp','1133','7777'],['equip3','ht','3333','2745']]
#dictionaries
carts = {'001':'Rev23', '002':'Rev11','003':'Rev7'}
#regular lists
stations = ("1", "2", "3", "4", "11", "Other")
最佳答案
看起来你需要的是 JSON文件。
示例:假设您有一个包含以下内容的 source.txt
:
{"hello": "world"}
然后,在您的 Python 脚本中,您可以使用 json.load() 将 JSON 数据结构加载到 Python 字典中。 :
import json
with open('source.txt', 'rb') as f:
print json.load(f)
打印:
{u'hello': u'world'}
您还可以使用 exec() ,但我真的不推荐它。这是一个仅用于教育目的的示例:
source.txt
:
d = {"hello": "world"}
你的脚本:
with open('test.txt', 'rb') as f:
exec(f)
print d
打印:
{'hello': 'world'}
希望对您有所帮助。
关于python - 在 Python 2.7 中如何将文本 (.txt) 文件作为 .py 文件读取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22668427/