将带有变量的文本文件导入 python

importing text files with variables into python

我的Objective:我创建的程序的目的是让用户输入元素的名称。然后 python 读入一个外部文件,该文件找到请求的元素分配给的值,最后打印出该值。

例如-

>>> helium
2

问题是我不知道如何让 python 解释看起来像这样的 txt 文件

hydrogen = 1
helium =  2
lithium = 3

作为代码。所以当我输入 print(lithium) 时,我得到一个错误。

我的要求: 谁能告诉我如何才能读出这些值并将它们打印出来。我不需要任何关于用户输入的帮助。

提前致谢。


更新

我用过这个代码:

import json
file = open("noble_gases.json","r")
elements = json.loads(file.read())

noble_gases.json 看起来像这样:

"helium" : 2,
"neon" : 10,
"argon" : 18,
"krypton" : 36,
"xenon" : 54,
"radon" : 86,

我现在收到这个错误:

Traceback (most recent call last):
  File "C:\Python34\Programs\Python Mini Project\finder.py", line 3, in <module>
    elements = json.loads(file.read())
  File "C:\Python34\lib\json\__init__.py", line 318, in loads
    return _default_decoder.decode(s)
  File "C:\Python34\lib\json\decoder.py", line 346, in decode
    raise ValueError(errmsg("Extra data", s, end, len(s)))
ValueError: Extra data: line 1 column 10 - line 7 column 1 (char 9 - 85)

感谢所有反对的人。我对回复的速度感到惊讶。


更新:

删除 json 文件中的最后一个逗号就成功了。 感谢所有提供帮助的人。 我还不能放弃评级,因为我还不到 15 级。 所以我给了你一条感谢信息。

项目完成

这可能有帮助

from collections import defaultdict
FILE = open("gas.txt","r")
GAS = defaultdict(str)
for line in FILE:
    gasdata = line.strip().split('=')
    GAS[gasdata[0].strip()] = gasdata[1].strip()

print GAS['carbon dioxide'] # 4

gas.txt 是:

hydrogen = 1
helium =  2
lithium = 3
carbon dioxide = 4

这应该可以满足您的需求:

gas = {}
with open('gas.txt', 'r') as gasfile:
    for line in gasfile:
        name, value = line.replace(' ', '').strip('=')
        gas[name] = value


# The gas dictionary now contains the appropriate key/value pairs

print(gas['helium'])

您可以解析文本文件(如其他人所建议的那样),如果您问我,这会带来一些不必要的复杂性,或者您可以使用对编程更友好的数据格式。我建议使用适合您的 json 或 yaml。

如果您使用的是json,您可以按如下方式进行:-

# rename gas.txt to gas.json
{
    'hydrogen': 1,
    'helium': 2,
    'lithium': 3
}

# in your code
import json
file = open('gas.json')
elements = json.loads(file.read())
print(elements['helium'])