importing text files with variables into python

2019-06-13 14:20发布

问题:

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.

For example -

>>> helium
2

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

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.

Thanks in advance.


UPDATE

I have used this code:

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

noble_gases.json looks like this:

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

And I am now getting this error:

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.


UPDATE:

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.

project finished

回答1:

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.

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


回答2:

This should do what you need:

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


回答3:

This may help

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 is:

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