简体   繁体   中英

Python file not reading data but putting repetetive values in list

Hi I am reading data from file in the class Patients and passing the content to appointment class method. when the content is split such that content[0] has ['130', 'Ali', 'Male', '22', 'Cough'] so I am putting these values and setting the Patient class properties. This is done in for loop so all objects from file read are added to list of Patient class. But in doing so it is repetitively adding only one row of data. Below is the code:

 //Text file Data:
          ID    PatientName     Gender      Age Disease
          130   Ali              Male       22  Cough
          132   Annile           Female     23  Corona
          133     sam            Male       24  Fever

I want list of patients to store 130-132-133 but instead it stores only 133 at all three positions of list. Dont know if object creation or passing for Patient class is an issue

//Patient.py

    class Patients:

         def __init__(self):
                 self.patient_id = ""
                 self.patient_name = ""
                 self.patient_age = ""
                 self.patient_gender = ""
                 self.patient_disease = ""
      
             def read_patient_file(self):
                     with open('PatientRecord.txt') as f:
                     content = f.readlines()
                     content = [x.strip() for x in content]
                     del content[0] // first row is of column names so removing it
                     return content

//Appointment.py

          def patientProgram(list_patient):
               Flag = True
               pat1 = Patients()
               while Flag:
               print("\nPress 1. To Create Patient Record ")
               print("Press 2. To View Patient Records ")
               print("Press 6. To Read Patient Record From File ")
               x = int(input("Please input from Menu Displayed Above which Operation to perform:"))
               if x == 1:
                  list_patient.append(AddPatient())

               elif x == 2:
                   print("**********")
                   print("Total Records in Memory for Patients:" + str(len(list_patient)))
                   for pat in list_patient:
                   print(f'patient_id = {pat.patient_id} for object {pat}')
                    
    
                elif x == 6: // this condition gives issue
                   content = []
                   content = pat1.read_patient_file() // content gets 3 rows of data from text file
                   j = 0
                   for i in content:
                       pat_id, name, gender, age, disease = str(content[j]).split()
                       print("FirstID: " + str(j)+ str(pat_id))
                       pat1.set_patient_record(pat_id, name, gender, age, disease)
                       list_patient.append(pat1)
                       j=j+1

                   print("Total Records for Patients in memory : " + str(len(list_patient)))
                   
             

           from Patients import Patients

           if __name__ == "__main__":
               list_patient = []

               Flag = True
               while Flag:
                  print("\nPress 1. For Patient Options ")
                  print("Press 2. For Doctor Options ")
                  print("Press 3. To Exit Program ")
                  x = int(input("Please Select From Menu:"))
                  if x == 1:
                     patientProgram(list_patient)
                 elif x==3:
                     break

    

You're only creating one Patients object. For each record in the file, you modify the pat1 object and append it to the list_patient list. So all the list elements are the same object.

You need to create a new object for each record in the file, not one object at the beginning.

Also, the read_patient_file() function should be a class method, since it doesn't use self for anything.

class Patients:

     def __init__(self):
             self.patient_id = ""
             self.patient_name = ""
             self.patient_age = ""
             self.patient_gender = ""
             self.patient_disease = ""

     @classmethod
     def read_patient_file(cls):
         with open('PatientRecord.txt') as f:
         content = f.readlines()
         content = [x.strip() for x in content]
         del content[0] // first row is of column names so removing it
         return content

def patientProgram(list_patient):
    Flag = True
    while Flag:
        print("\nPress 1. To Create Patient Record ")
        print("Press 2. To View Patient Records ")
        print("Press 6. To Read Patient Record From File ")
        x = int(input("Please input from Menu Displayed Above which Operation to perform:"))
        if x == 1:
            list_patient.append(AddPatient())

        elif x == 2:
            print("**********")
            print("Total Records in Memory for Patients:" + str(len(list_patient)))
            for pat in list_patient:
                print(f'patient_id = {pat.patient_id} for object {pat}')
                
        elif x == 6: // this condition gives issue
            content = []
            content = Patients.read_patient_file() // content gets 3 rows of data from text file
            j = 0
            for i in content:
                pat1 = Patients()
                pat_id, name, gender, age, disease = str(content[j]).split()
                print("FirstID: " + str(j)+ str(pat_id))
                pat1.set_patient_record(pat_id, name, gender, age, disease)
                list_patient.append(pat1)
                j=j+1

            print("Total Records for Patients in memory : " + str(len(list_patient)))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM