简体   繁体   English

Python 文件不读取数据但将重复值放入列表

[英]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.嗨,我正在从 class 患者中的文件中读取数据,并将内容传递给预约 class 方法。 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.当内容被拆分使得 content[0] 具有 ['130', 'Ali', 'Male', '22', 'Cough'] 所以我输入这些值并设置 Patient class 属性。 This is done in for loop so all objects from file read are added to list of Patient class.这是在 for 循环中完成的,因此来自文件读取的所有对象都被添加到患者 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.我希望患者列表存储 130-132-133,但它在列表的所有三个位置仅存储 133。 Dont know if object creation or passing for Patient class is an issue不知道为患者 class 创建或传递 object 是否存在问题

//Patient.py //病人.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 //约会.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.您只创建了一个Patients object。 For each record in the file, you modify the pat1 object and append it to the list_patient list.对于文件中的每条记录,您将pat1 object 和 append 修改为list_patient列表。 So all the list elements are the same object.所以所有的列表元素都是相同的 object。

You need to create a new object for each record in the file, not one object at the beginning.您需要为文件中的每条记录创建一个新的 object,而不是一开始就创建一个 object。

Also, the read_patient_file() function should be a class method, since it doesn't use self for anything.此外, read_patient_file() function 应该是 class 方法,因为它不使用self做任何事情。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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