Jasper StaTham
Jasper StaTham

Reputation: 117

Python File overwrite each time i added a new line

i am doing a program where the user can add a student from student.txt into a new .txt file with a output like this

this is my content of 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

this is my code

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

what i want my output to be

Module 201707001 Michael_Tan
Module 201707002 Richard_Lee
Module 201707003 Jean_Yip

but the output has been overwrite in only one line even though i add the module 3 time

Module 201707003 Jean_Yip

Upvotes: 1

Views: 2982

Answers (1)

Adi219
Adi219

Reputation: 4814

Change:

with open(home + "\\Desktop\\PADS Assignment\\210CTStudentModule.txt", "w") as f:

to:

with open(home + "\\Desktop\\PADS Assignment\\210CTStudentModule.txt", "a") as f:

You are using "w" which overwrites any previous content. You need "a", which appends to the existing file without overwriting.

Sometimes, users can get locked out of files which they open and write to in programs and then those files become read-only if they aren't closed. It's a good idea to add f.close() and f1.close() at the end of your askModule() function as you don't need to keep those files open any longer.

Upvotes: 5

Related Questions