将带有变量的文本文件导入python [英] importing text files with variables into python

查看:193
本文介绍了将带有变量的文本文件导入python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My Objective: The purpose the program I am creating is to have the user enter the name of an element. Then python reads into an external file that finds the value that the requested element is assigned to and finally the value is printed out.

例如-

>>> helium
2

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

The problem is I don't know how to get python to interpretate the txt file that looks like this

hydrogen = 1
helium =  2
lithium = 3

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

as code. So when I enter print(lithium), I get an error.

我的要求: 有人可以告诉我如何将其读取到可以读出并打印出来的值.在用户输入和所有这些方面,我不需要任何帮助.

My request: Could someone show me how I can get it to the point that I can read out the values and print them out. I don't need any help with the user input and all of that.

谢谢.

更新

我使用了以下代码:

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

noble_gases.json看起来像这样:

noble_gases.json looks like this:

"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)

感谢所有对立的人.我对回应的速度感到惊讶.

Thanks to everyone who has contrabuted. I am amazed by the speed of the responses.

更新:

删除json文件中的最后一个逗号就可以了. 感谢所有提供帮助的人. 由于我不是15级,因此我还不能放弃评分. 所以我给了你一封谢谢你的信息.

Removing the final comma in the json file did the trick. Thanks to everyone who helped. I can't give up ratings yet since i'm not level 15. So I gave you a thank you message instead.

推荐答案

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

You can parse the text file(as others suggested) which if you ask me would be little unnecessary complexity, or you can use more programming friendly data format. I suggest using json or yaml whichever suits you.

如果您使用的是json,则可以执行以下操作:-

If you are using json, than you can do as follows:-

# 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'])

这篇关于将带有变量的文本文件导入python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆