简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM