如何将for循环的内容打印到txt文件中?Python

x6492ojm  于 2022-12-20  发布在  Python
关注(0)|答案(1)|浏览(204)

所以我试图找出有多少学生,然后要求那一数量的学生提供他们的身份证,并将所有的学生证打印成一个txt文件,后面跟着虚线(这样他们就可以在文件上签名)
这是我的代码:

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"))

我的问题是只有最后一个学生输入的内容被转移到文件中,我也不知道我应该把文件设置为a还是w,对此有任何见解都会很有帮助。
我想我必须以某种方式循环f. write in,但不知道如何做到这一点?

ajsxfq5m

ajsxfq5m1#

只有最后一个学生被记录,因为您在代码末尾调用write方法,在for循环之外。

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"))

关于"a""w""a"模式会把新行附加到文件中,而"w"会覆盖它。

相关问题