0

So, i have this problem:

i have three txt-files: number1.txt, number2.txt and number3.txt.

number1.txt have this number: 10 and number2.txt have this number too.

So, what i want to do, is to sum up these numbers and add result to number3.txt.

I have already this code:

number1 = open("files/number1.txt", encoding="utf-8").read()
number2 = open("files/number2.txt", encoding="utf-8").read()
number3 = open("files/number3.txt", "w", encoding="utf-8")
result = float(number1) + float(number2)
number3.write(str(result))

But nothing shows up on the number3.txt. I have no idea why this is not working. I know this is maybe an pretty stupid question, but i hope you guys can help me.

I have python 3.4.3.

2
  • Have you tried print(result)? Commented Oct 8, 2015 at 11:56
  • Yes, and python printed the right result, but nothing still doesn't appear on number3.txt Commented Oct 8, 2015 at 12:00

2 Answers 2

1

It's a good idea to always close your files, and the way you're doing it all of them remain open. In order to do that, use the with command:

with open("files/number1.txt", encoding="utf-8") as f:
  number1 = f.read()
with open("files/number2.txt", encoding="utf-8") as f:
  number2 = f.read()
result = float(number1) + float(number2)
with open("files/number3.txt", "w", encoding="utf-8") as f:
  f.write(result)

That way you don't have to worry about closing your files, since they get closed automatically.

Sign up to request clarification or add additional context in comments.

Comments

0

You haven't closed or flushed the file. Make sure you have a number3.close().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.