从文本文件导入变量并在方程式中使用

时间:2018-08-27 21:38:14

标签: python variables import save

如何从.txt导入数据并将其声明为新变量?并且每次将输出保存为带有我的输入变量和解决方案的新文本文件。

我有一个文本文件“ values.txt”,其中包括:

a = k*t/r

(以“ enter”分隔)

我也有python文件放在等式中: txt = open("values.txt").read() print(txt) a = k*t/r print(a) txt.close()

现在我只弄清楚了这些:

import java.util.Scanner;
import java.util.Stack;

// use Capital letters in the beginning of class names
public class BracketCheck {
    public static void main(String[] args) {

        Stack<Character> stack = new Stack<>();
        Scanner input = new Scanner(System.in);
        String buff;

        System.out.println("please enter brackets & text");
        buff = input.nextLine();
        input.close();
        // using java8 makes iterating over the characters of a string easier
        buff.chars().forEach(current -> {
            // if <current> is an opening bracket, push it to stack
            if (current == '(' || current == '{' || current == '[') {
                stack.push((char) current);
            }
            // if <current> is a closing bracket, make sure it is matching an opening
            // bracket or alert and return
            else if (current == ')' || current == '}' || current == ']') {
                if (!match(stack, (char) current)) {
                    System.out.println("no good");
                    return;
                }
            }
        });
        // if, after we finished iterating the string, stack is empty, all opening
        // brackets had matching closing brackets
        if (stack.isEmpty()) {
            System.out.println("bout time......");
        }
        // otherwise, alert
        else {
            System.out.println("woah");
        }
    }

    private static boolean match(Stack<Character> stack, Character closer) {
        // if stack is empty, the closer has no matching opener
        if (stack.isEmpty()) {
            return false;
        } else {
            // get the most recent opener and verify it matches the closer
            Character opener = stack.pop();
            if (opener == '(' && closer == ')')
                return true;
            else if (opener == '[' && closer == ']')
                return true;
            else if (opener == '{' && closer == '}')
                return true;
            else
                return false;
        }
    }
}

5 个答案:

答案 0 :(得分:1)

读取文件。以\r\n分隔。通过在=

上拆分来获取值
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()

当处理较少的值时,此方法很好,否则请使用csvreader

答案 1 :(得分:1)

通常,您可以创建一个dict variable_name:value以便在方程式中使用。

例如:

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

答案 2 :(得分:0)

我更喜欢将.txt存储为json文件。我的filename看起来像:

{ "foo":
    "bar"
}

从这里,您可以拥有

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

答案 3 :(得分:0)

您可以通过遍历文件来读取文件中的每一行。然后,您可以用=字符分隔每行。

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

我创建了一个名为constants的字典,该字典可根据需要为每个常数保存任意数量的name : value对。然后,您所需要做的就是修改您的计算,以从常量字典中得出它们的值。

这允许您添加任意数量的常量:通过不对任何变量进行硬编码,可以添加可扩展性。

答案 4 :(得分:0)

如果您可以控制输入文件的格式,请使其尽可能简单。将所有三个数字放在同一行(如10 20 8.5中),并用以下命令读取:

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