import variables from a text file and use it in an equation

Viewed 9472

How I can import data from .txt and state them as my new variables? And each time save an output as a new text file with my input variables and the solution.

I have text file "values.txt" which includes of:

k=10
t=20
r=8.5

(separated by "enter")

and I also have python file in where is put the equation: a = k*t/r

for now I've figured out only these:

txt = open("values.txt").read()
print(txt)    

a = k*t/r
print(a)

txt.close()
5 Answers

I prefer storing my .txt as a json file. My filename looking like :

{ "foo":
    "bar"
}

From here, you can have

import json
#Read JSON data into the datastore variable
if filename:
    with open(filename, 'r') as f:
        datastore = json.load(f)

#Use the new datastore datastructure
print datastore["foo"]

More generally you may create a dict variable_name:value to use in your equations.

For instance:

variables = {}

with open("values.txt") as f:
    for line in f:
        name, value = line.split("=")
        variables[name] = float(value)

k = variables["k"] 
t = variables["t"] 
r = variables["r"] 

a = k*t/r

Read the file. Separate by \r\n. Fetch the values by splitting on =

txt = open("values.txt").readLines()
k = float(txt[0].split("=")[0])
t = float(txt[1].split("=")[0])
r= float(txt[2].split("=")[0])
a = k*t/r
print(a)

txt.close()

This method is fine when dealing with less values otherwise use csvreader

You can read each line in the file by iterating over it. You can then split each line by the = character.

constants = {}
with open('values.txt', 'r') as f:
    for line in f:
        name, val = line.split('=')
        constants[name] = float(val)

>>> constants['a']
10.0
>>> constants['t']
20.0
>>> constants['r']
8.5

I've created a dictionary called constants which holds any number of name : value pairs as you like for each constant. Then all you need to do is amend your calculations to derive their values from the constants dictionary.

This allows you to add as many constants as you like: by not hard coding any variables, you add extensibility.

If you have control over the format of the input file, make it as simple as possible. Put all three numbers on the same line (as in 10 20 8.5) and read with:

with open("values.txt") as infile:
    k, t, r = map(float, infile.read().split())
Related