How do I calculate operations from a txt file?
Question:
So I have a homework to write those expressions in a notepad, this is my input file:
4+1
12-3
2*182
8/2
then, I have to write a program in idle that will read that, line by line, that will solve the operations and return them in a new output file called ‘iesire.txt’, like this:
4+1=5
12-3=9
2*182=364
8/2=4
import calculator
inp = open('./expresii.txt', 'r')
read = inp.readlines()
with open('./iesire.txt', 'w') as output:
for line in read:
res = eval(line.strip())
print(output.write(line.strip()+ "=" + str(res) + 'n'))
when I run this code , the following gets printed, and I don’t understand why:
6
7
10
8
Answers:
The code works perfectly fine and i believe you should get the correct result from the text file. However, what you are printing is actually the number of characters in the line you have added to the text file. If you wanted to print the result of the calculation as well as add it to the text file then you could do something like this.
import calculator
inp = open('./expresii.txt', 'r')
read = inp.readlines()
with open('./iesire.txt', 'w') as output:
for line in read:
res = eval(line.strip())
text = line.strip() + "=" + str(res) + 'n'
output.write(text)
print(text)
So I have a homework to write those expressions in a notepad, this is my input file:
4+1
12-3
2*182
8/2
then, I have to write a program in idle that will read that, line by line, that will solve the operations and return them in a new output file called ‘iesire.txt’, like this:
4+1=5
12-3=9
2*182=364
8/2=4
import calculator
inp = open('./expresii.txt', 'r')
read = inp.readlines()
with open('./iesire.txt', 'w') as output:
for line in read:
res = eval(line.strip())
print(output.write(line.strip()+ "=" + str(res) + 'n'))
when I run this code , the following gets printed, and I don’t understand why:
6
7
10
8
The code works perfectly fine and i believe you should get the correct result from the text file. However, what you are printing is actually the number of characters in the line you have added to the text file. If you wanted to print the result of the calculation as well as add it to the text file then you could do something like this.
import calculator
inp = open('./expresii.txt', 'r')
read = inp.readlines()
with open('./iesire.txt', 'w') as output:
for line in read:
res = eval(line.strip())
text = line.strip() + "=" + str(res) + 'n'
output.write(text)
print(text)