Home > Software engineering >  How to get variable values from a txt file with a specified format?
How to get variable values from a txt file with a specified format?

Time:06-15

I am writing a program that solves quadratic equations, with the variables assigned from a .txt file, with this specific format:

The text file will contain lines of comma separated text – each line contains three floating point numbers. The first number is the value for A, the second number is the value for B, and the third number is the value for C.

Now I have my code mostly written out I am just unsure how I would assign these variables from a .txt file. Here is my current code:

print("\nWelcome to the Blockhouse Bay College Quadratic Equation Program")

file = input("\nPlease input text file name: ")
        file = file   ".txt"
        text_file = open(file, "r")

import math


# function for finding roots
def equationroots( a, b, c):

    # calculating discriminant using formula
    dis = b * b - 4 * a * c
    sqrt_val = math.sqrt(abs(dis))

    # checking condition for discriminant
    if dis > 0:
        print("There are two distinct roots ")
        print((-b   sqrt_val)/(2 * a))
        print((-b - sqrt_val)/(2 * a))

    elif dis == 0:
        print("There is one real root")
        print(-b / (2 * a))

    # when discriminant is less than 0
    else:
        print("Complex Roots")
        print(- b / (2 * a), "   i", sqrt_val)
        print(- b / (2 * a), " - i", sqrt_val)

# Driver Program
#<---------------Need these variables assigned to lines from .txt file
a = 1
b = 10
c = -24

# If a is 0, then incorrect equation
if a == 0:
        print("Cannot be a quadratic equation if a is zero")

else:
    equationroots(a, b, c)

Note: Please note at the start of my code I have asked the user to input the file name, I still need to work on this as I need to create an error message for when the file does not exist. Just ignore this as I can fix that later.

CodePudding user response:

with open('file.txt'):
    content = f.read()

for line in content.splitlines():
   a, b, c = map(float, content.split(','))

Complete program:

print("\nWelcome to the Blockhouse Bay College Quadratic Equation Program")
import math


# function for finding roots
def equationroots( a, b, c):

    # calculating discriminant using formula
    dis = b * b - 4 * a * c
    sqrt_val = math.sqrt(abs(dis))

    # checking condition for discriminant
    if dis > 0:
        print("There are two distinct roots ")
        print((-b   sqrt_val)/(2 * a))
        print((-b - sqrt_val)/(2 * a))

    elif dis == 0:
        print("There is one real root")
        print(-b / (2 * a))

    # when discriminant is less than 0
    else:
        print("Complex Roots")
        print(- b / (2 * a), "   i", sqrt_val)
        print(- b / (2 * a), " - i", sqrt_val)


filename = input("\nPlease input text file name: ")

with open(filename   '.txt'):
    content = f.read()

for line in content.splitlines():
    a, b, c = map(float, content.split(','))

    # If a is 0, then incorrect equation
    if a == 0:
        print("Cannot be a quadratic equation if a is zero")

    else:
        equationroots(a, b, c)

CodePudding user response:

you could read the file like this:

f = open(file_name,"r")

for line in f.readlines():
  a,b,c = map(float,line.split(","))

  # now call your function
  if a == 0:
    print("Cannot be a quadratic equation if a is zero")
  else:
    equationroots(a, b, c)

we started by opening the file then we iterate over the lines using file.readlines() then for every line we splitted the values and converted all of them to a float using map()

CodePudding user response:

Try this:

I had to move some of your code around, but I left inline comments to explain what I changed. I also included a check to make sure the path exists.

import math   # Python convention is to put imports at the top
import os

print("\nWelcome to the Blockhouse Bay College Quadratic Equation Program")

# function for finding roots
def equationroots( a, b, c):

    # calculating discriminant using formula
    dis = b * b - 4 * a * c
    sqrt_val = math.sqrt(abs(dis))

    # checking condition for discriminant
    if dis > 0:
        print("There are two distinct roots ")
        print((-b   sqrt_val)/(2 * a))
        print((-b - sqrt_val)/(2 * a))

    elif dis == 0:
        print("There is one real root")
        print(-b / (2 * a))

    # when discriminant is less than 0
    else:
        print("Complex Roots")
        print(- b / (2 * a), "   i", sqrt_val)
        print(- b / (2 * a), " - i", sqrt_val)



file = input("\nPlease input text file name: ")
file = file   ".txt"

if os.path.exists(file):   # check if file exists
    with open(file, "rt") as text_file:  # using a with statement is 
                                         # preferred over directly 
                                         # opening the file
        for line in text_file:  # iterate through lines of file

            # the next line splits the `line` by "," commas, 
            # removes whitespace and casts each item to float
            a,b,c = [float(i.strip()) for i in line.split(',')]
            if a == 0:
                print("Cannot be a quadratic equation if a is zero")
            else:
                equationroots(a, b, c)
else:
    # print some message
  • Related