Home > Software design >  How to print contents of a for loop into a txt file? Python
How to print contents of a for loop into a txt file? Python

Time:12-15

So I am trying to find out how many students there are, then ask that amount of students for their ID and print all the student IDs into a txt file followed by a dotted line(so they can sign the document)

This is my code so far:

i = 0
no_students = int(input("How many students are registering?"))
for student in range(i, no_students):
    if no_students > i:
        s_id = input("Enter your student ID: ")
        i  = 1

with open("reg_form.txt", "a") as f:
    f.write(str(f"Student ID: {s_id} ....................... \n"))


My issue is that only the last student input is transferred to the file. Also I don't know whether I should have the file be a or w. Any insight on that would be helpful.

I think I have to somehow loop the f.write in but not sure how to do that?

CodePudding user response:

Only the last student is being recorded because you are calling the write method at the end of your code, outside of the for loop.

i = 0
no_students = int(input("How many students are registering?"))
for student in range(i, no_students):
    if no_students > i:
        s_id = input("Enter your student ID: ")
        i  = 1

    with open("reg_form.txt", "a") as f:
        f.write(str(f"Student ID: {s_id} ....................... \n"))

And about the "a" or "w", the "a" mode is going to append the new line to your file. And the "w" is going to overwrite it. Python's input and output documentation

  • Related