我正在做一个程序,用户可以将student.txt中的学生添加到一个新的.txt文件中,并带有这样的输出
这是我对student.txt的内容
201707001 Michael_Tan
201707002 Richard_Lee_Wai_Yong
201707003 Jean_Yip
201707004 Mark_Lee
201707005 Linda_Wong
201707006 Karen_Tan
201707007 James_Bond
201707008 Sandra_Smith
201707009 Paul_Garcia
201707010 Donald_Lim
这是我的代码
from pathlib import Path
home = str(Path.home())
def askModule():
module = input("Enter the module that you want to register to: ")
print("Who you want to register into the module?\n\n")
studentNumber = input("Enter student number: ")
studentName = input("Enter student name: ")
with open(home + "\\Desktop\\PADS Assignment\\210CTStudentModule.txt", "w") as f:
with open(home + "\\Desktop\\PADS Assignment\\Student.txt", "r") as f1:
for line in f1:
stdId, stdName = line.strip().split(" ", 1)
if studentNumber == stdId:
if studentName == stdName:
f.write(module + " " + stdId + " " + stdName)
break
else:
print("Unsuccessful")
askModule()
我希望我的输出是什么
Module 201707001 Michael_Tan
Module 201707002 Richard_Lee
Module 201707003 Jean_Yip
但即使我添加模块3次
,输出也只在一行中覆盖Module 201707003 Jean_Yip
答案 0 :(得分:4)
变化:
with open(home + "\\Desktop\\PADS Assignment\\210CTStudentModule.txt", "w") as f:
为:
with open(home + "\\Desktop\\PADS Assignment\\210CTStudentModule.txt", "a") as f:
您正在使用"w"
覆盖之前的所有内容。您需要"a"
,它会附加到现有文件而不会覆盖。
有时,用户可能会被锁定在他们打开并在程序中写入的文件中,如果这些文件未关闭,则会变为read-only
。最好在f.close()
函数的末尾添加f1.close()
和askModule()
,因为您不再需要保持这些文件的打开状态。