读入文本文件的十进制数字值并将其分配给变量

时间:2019-07-03 20:42:09

标签: python-3.x

无法获得将文本文件十进制数字分配给变量的程序。

搜索了youtube和互联网,没有发现任何帮助。

with open("Inputpydata.txt", "r") as fo:
    line = fo.readline()
    while line:
        print(line.strip())
        avalue = line[4]
    line = fo.readline()
    while line:
        print(line.strip())
        bvalue = line[4]
    line = fo.readline()
    while line:
        print(line.strip())
        cvalue = line[4]
    line = fo.readline()

    a = float(avalue)
    b = float(bvalue)
    c = float(cvalue)

    sum = a + b + c

    print("a = ", a)
    print("b = ", b)
    print("c = ", c)
    print("sum = ", sum)

输入文本文件包含3行,其中a = 1.0 b = 2.0 c = 3.0,总和应为6.0

修改后的工作版本,

with open("Inputpydata.txt", "r") as fo:
    line = fo.readline()
    avalue = line[4]
    line = fo.readline()
    bvalue = line[4]
    line = fo.readline()
    cvalue = line[4]

    a = float(avalue)
    b = float(bvalue)
    c = float(cvalue)

    d = a + b + c

    print("a =", a)
    print("b =", b)
    print("c =", c)
    print()
    print("d =", d)

with open("Outputpydata.txt", "w") as fo:
    fo.write("a = " + str(a) + "\n")
    fo.write("b = " + str(b) + "\n")
    fo.write("c = " + str(c) + "\n")
    fo.write("\n")
    fo.write("d = " + str(d))

2 个答案:

答案 0 :(得分:0)

首先,在这3个循环中没有太多意义,因为到第一个循环退出时,其他两个循环甚至都不会进入。仅仅因为它们都具有相同的条件,所以逻辑要求...

第二种方法是从文件中读取行的简便方法,但我看不到您认为=符号的位置。我想你的意思是:

with open("Inputpydata.txt", "r") as fo:
    line = fo.readline().strip()
    print(line)
    avalue = line[4:]
    line = fo.readline().strip()

    print(line)
    bvalue = line[4:]
    line = fo.readline().strip()

    print(line)
    cvalue = line[4:]

    a = float(avalue)
    b = float(bvalue)
    c = float(cvalue)

    sum = a + b + c

    print("a = ", a)
    print("b = ", b)
    print("c = ", c)
    print("sum = ", sum)

您可以使其更加通用:

with open("Inputpydata.txt", "r") as fo:
    values = []
    for line in fo:
        line_split = line.split("=")
        value = float(line_split[1].strip())
        values.append(value)

        print("a = ", values[0])
        print("b = ", values[1])
        print("c = ", values[2])
        print("sum = ", sum(values))

答案 1 :(得分:0)

如果您选择使用pandas,则可以轻松地执行此任务:

import pandas as pd

df = pd.read_csv("Inputpydata.txt",header=None,names=['variables','values'], sep="=")
d = df['values'].sum()
print(d, type(d))

输出->

6.0 <class 'numpy.float64'>

其中Inputpydata.txt文件包含:

a = 1.0
b = 2.0
c = 3.0