Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I calculate operations from a txt file?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

6
7
10
8

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading