繁体   English   中英

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

[英]Python file not reading data but putting repetetive values in list

嗨,我正在从 class 患者中的文件中读取数据,并将内容传递给预约 class 方法。 当内容被拆分使得 content[0] 具有 ['130', 'Ali', 'Male', '22', 'Cough'] 所以我输入这些值并设置 Patient class 属性。 这是在 for 循环中完成的,因此来自文件读取的所有对象都被添加到患者 class 列表中。 但是这样做只会重复添加一行数据。 下面是代码:

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

我希望患者列表存储 130-132-133,但它在列表的所有三个位置仅存储 133。 不知道为患者 class 创建或传递 object 是否存在问题

//病人.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

//约会.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

    

您只创建了一个Patients object。 对于文件中的每条记录,您将pat1 object 和 append 修改为list_patient列表。 所以所有的列表元素都是相同的 object。

您需要为文件中的每条记录创建一个新的 object,而不是一开始就创建一个 object。

此外, 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