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 to calculate the sum of numbers in one file and print the result into another file in Python?

We have an input text file that contains 2 integers a and b. Calculate the 2 numbers just entered and print the value of the sum into the output text file.
Here is what I’ve tried so far:

x= open ("input.txt", "r")
Sum=[]
z = x.readlines()
for i in z:
if i.isdigit():
    Sum += (z)
x.close()
y= open ("output.txt", "w")
y.write(str(Sum))
y.close()

>Solution :

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

The lines you’re reading from the input file are strings so you need to convert them to ints. Also, each line will have a newline character ‘\n’ at the end which will need to be removed before you can successfully convert each line to an int.

There are also several other issues with your code example. Sum is a list, but aren’t you trying to add each int from input.txt? Also if i.isdigit() is not indented. try, except can be used instead though.

x = open("input.txt", "r")
Sum = 0
z = x.readlines()
for i in z:
    try:
        Sum += int(i.strip())
    except ValueError:
        pass

x.close()
y= open ("output.txt", "w")
y.write(str(Sum))
y.close()
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