如何在python中使用append将多个输入写入文本文件?

时间:2018-11-15 14:35:13

标签: python python-3.x python-3.7

while True:
    def student_info(name,age,gender):
        print("The student name is:",name)
        print("The student age is:",age)
        print("The student gender is:",gender)
    print("*"*70)
    Student_name=input("Enter Student name:")
    Student_age=input("Enter Student age:")
    Student_gender=input("Enter Student gender:")


    print("*"*70)

    with open('Try1.txt', 'w') as f:
      f.write(Student_name+" "+Student_age+" "+Student_gender)


    student_info(Student_name,Student_age,Student_gender)

    print("if you want add more students press 1 ")
    user_input=input("Enter:")
    if user_input=="1":

        with open('Try1.txt', 'a') as f:
          f.write(Student_name+" "+Student_age+" "+Student_gender)
        student_info(Student_name,Student_age,Student_gender)

我想在课文中增加更多的学生,但是当我再添加一个学生时,前一个会被删除。.在此方面,我需要帮助。

2 个答案:

答案 0 :(得分:1)

首先,在用户未输入1的情况下,您有时需要break,否则您想进行continue循环。还有您在代码末尾复制数据插入的地方。

尝试以下方法:

while True:
    def student_info(name,age,gender):
        print("The student name is:",name)
        print("The student age is:",age)
        print("The student gender is:",gender)
    print("*"*70)
    Student_name=input("Enter Student name:")
    Student_age=input("Enter Student age:")
    Student_gender=input("Enter Student gender:")


    print("*"*70)

    with open('Try1.txt', 'a') as f:
      f.write('\n'+Student_name+" "+Student_age+" "+Student_gender)


    student_info(Student_name,Student_age,Student_gender)

    print("if you want add more students press 1 ")
    user_input=input("Enter:")
    if user_input=="1": continue
    else: break

答案 1 :(得分:1)

问题在于第一个openwhile循环内,只是将其带到外面。我在重新格式化您的代码:

def student_info(name,age,gender):
    print("The student name is:",name)
    print("The student age is:",age)
    print("The student gender is:",gender)

while True:
    print("*"*70)
    Student_name=input("Enter Student name:")
    Student_age=input("Enter Student age:")
    Student_gender=input("Enter Student gender:")


    print("*"*70)

    with open('Try1.txt', 'a') as f:
      f.write(f"{Student_name} {Student_age} {Student_gender}")

    student_info(Student_name, Student_age, Student_gender)

    print("if you want add more students press 1 ")
    user_input=input("Enter:")
    if user_input != "1":
        break