Stack Exchange
How can I write the print output to a text file in Python?
I want to write the print output from the math to a text file but I can't make it work.
This is my code:
huur = int(input("Hoeveel bedraagt de huur per jaar? "))

percentage = int(input("Percentage verhoging elk jaar: "))/100

tijd = int(input("Hoeveel jaar wordt de opslagruimte gehuurd? "))

x = 0
while x < tijd:
    huur += huur * percentage
    x += 1

    print(f"Kosten huur jaar" ,x, huur,)

I tried it with with open("uitvoer.txt", "w") as f:
f.write(f"result: {print}")
but it didn't work.

What is print in f.write(f"result: {print}")?

I just tried that to see if it would save the output from the print to a text file but it didn't work.

The print() function accepts a file argument: print("Kosten huur jaar", x, huur, file=f) should work after having opened f as you suggested.

Does this answer your question? How to redirect 'print' output to a file?

The problem is that in f.write(f"result: {print}") you are using a variable called print while it is not a variable but the name of a builtin function called "print()". Instead, create a variable and use that instead. For example:
while x < tijd:
    huur += huur * percentage
    x += 1
    answer = " ".join(["Kosten huur jaar" ,str(x), str(huur)])
    print(answer)
    with open("uitvoer.txt", "a") as f:
        f.write(f"\n{answer}")

I am assuming that you want each result in the while loop to be added to the file. Open the file in append mode. Using append mode, you can add each answer to the end of the file.
However, there are other methods you can use as well. Have a look here: How to redirect 'print' output to a file?.

Thank you for your answer!
I tried it but I get this error:
answer = " ".join(["Kosten huur jaar" ,x, huur])
TypeError: sequence item 1: expected str instance, int found

You have to turn all numbers into strings when concatenating: answer = " ".join([ "Kosten huur jaar" , str(x),  str(huur) ]). The print-function does that automatically.

I've edited the answer. Check.
