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()
CodePudding user response:
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()
CodePudding user response:
You can use the eval()
function to make it easier...
with open('output.txt', 'w') as out:
with open('input.txt', 'r') as inp:
out.write(str(eval(inp.read())))
input.txt
:
1 1
output.txt
2