0

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.

Pita
  • 11
  • What is `print` in `f.write(f"result: {print}")`? – 吴慈霆 Dec 12 '22 at 02:40
  • I just tried that to see if it would save the output from the print to a text file but it didn't work. – Pita Dec 12 '22 at 02:43
  • The `print()` function accepts a file argument: `print("Kosten huur jaar", x, huur, file=f)` should work after having opened `f` as you suggested. – joanis Dec 12 '22 at 03:13
  • Does this answer your question? [How to redirect 'print' output to a file?](https://stackoverflow.com/questions/7152762/how-to-redirect-print-output-to-a-file) – joanis Dec 12 '22 at 03:16

1 Answers1

0

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?.

Abu Hurairah
  • 146
  • 7
  • 2
    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 – Pita Dec 12 '22 at 02:51
  • 1
    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. – areop-enap Dec 12 '22 at 02:58
  • I've edited the answer. Check. – Abu Hurairah Dec 12 '22 at 06:48