Importing Text Files With Variables Into 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 requeste
Solution 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'])
Solution 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'])
Solution 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
Post a Comment for "Importing Text Files With Variables Into Python"