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

标签 python file python-2.7 module

我有一个共享文件夹,其中包含一个文本文件,我希望我的程序像引用 .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/

相关文章:

python - 如何在 SimpleHTTPServer 中写入消息

java - 如何从 java 或 Android 中的字符串制作 XML 文档?

iphone - 如何在 iPhone 或 iPad 中从 ppt 文件中的幻灯片中获取图像?

python - python3创建scrapy项目的方法

python - ELI5 : How do I make these FFT-related lists act properly?

python - 从 Python 连接到 Apache Drill

python - Anaconda:使用 environment.yml 从特定 channel 安装特定包

python - 如何用分类值替换列中的一系列数字,假设数字范围是 float 类型

javascript - 从另一个 JavaScript 编写一个 JavaScript 文件

python - 在 Django 中使用 OneToOneField