Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I'm trying to use the values inside a .txt file to be able to use it in an equation

Tags:

python

I have a .txt file which has these values 10,20,30,40,50. It only has a single row but, with multiple columns. I'm having a hard time on how to use each column as a single value to be used in an equation.

I have the code below:

val = input('Enter the text file name: ')
print('Opening text file: ', val)

try:
    file = open(val + '.txt', 'r').readlines()

    for row in file:
        price_raw = row

except FileNotFoundError:
    print('File name not found.')

price = int(price_raw)
balanceA = 100
balanceB = 100
total_balance = (balanceA + balanceB) * price

print(total_balance)

I have tried converting row into an integer but, it prompts

ValueError: invalid literal for int() with base 10

I have tried to use print(type(row)) and the value I am getting from the file is a string.

How can I extract all the values in the .txt file and use them in the equation for total_balance?

For the first column on the .txt file, 10, e.g. total_balance = (100 + 100) * 10. Then the next column, which is 20, e.g. total_balance = (100 + 100) * 20

Is it possible for the total_balance to contains different values for each of the price value?

How would I approach on doing this?

like image 707
Dennis Manicani Jr. Avatar asked Sep 06 '25 03:09

Dennis Manicani Jr.


1 Answers

You can easily read the line into an array of integers with the following snippet:

raw_prices = price_raw.split(",")
prices = list(map(int, raw_prices))

Some explanation:

  • The price_raw.split(",") breaks your input at every "," it finds and returns a list of strings with the numpers.
  • The map then converts this list to integer.
  • Finally, the list makes a list from the map object.
like image 180
rammelmueller Avatar answered Sep 07 '25 21:09

rammelmueller



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!