如何在Python 2.7中将文本(.txt)文件读取为.py文件?

2 投票
2 回答
1385 浏览
提问于 2025-04-18 00:01

我有一个共享文件夹,里面有一个文本文件,我希望我的程序能把它当作一个 .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") 

2 个回答

3

如果你完全信任这个来源的 .txt 文件,可以看看 execfile 这个函数。

3

看起来你需要的是一个 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'}

希望这些对你有帮助。

撰写回答