0

I am creating a program that manages a file for patients; it's part of a project. I've created a log file. I've pickled the information of the patients as instances in the file. In the following code, I'm attempting to traverse the file and receive the patient instance that satisfies the given condition:

def searchpatientnumber():

    patobj=open("G:\patientregister.log", "ab+")
    test=patient() #the patient class
    patientid=raw_input("Enter patient register number:")
    import pickle
    test=pickle.load(patobj)
    try:
        while True: #I hoped that this loop will help read the whole file
            if test.registerno==patientid: #registerno is a datamember
            test.displaynumber() #member function
            break
        else:
            print "Patient not registered, try again."
            break
    except EOFError:
        patobj.close()

The code works, however, it is only able to read the first instance in the file but can't read the rest. Can I please get a way to traverse all the instances of a binary file? Thank you.

  • pickled : process of using vinegar on vegetables to make them more durable - made me giggle - wait .. thats a python class? LOL – Patrick Artner Nov 18 '17 at 13:32
  • @Patrick you realise there's a `pickle` module to python for serializing objects, right? – roganjosh Nov 18 '17 at 13:34
  • @roganjosh after seeing the `import pickle` in the mids of the `def` - yes ;) - just now erading up on https://docs.python.org/3/library/pickle.html – Patrick Artner Nov 18 '17 at 13:35
  • 1
    Why don't you just pickle a list of instances? – Aran-Fey Nov 18 '17 at 13:37
  • 2
    Possible duplicate of [Saving and loading multiple objects in pickle file?](https://stackoverflow.com/questions/20716812/saving-and-loading-multiple-objects-in-pickle-file) – Wander Nauta Nov 18 '17 at 13:37
  • Please fix the indentation in your code. It's not clear where `break` resides with regards to your `while` loop. – roganjosh Nov 18 '17 at 13:39
  • My guess would be you pickled multiple patients, so unpickling should give you some kind of `list` back - please provide the pickling code. I somehow miss some kind of iteration on the unpickled test-Object that traverses the patients and checks each one if its registerno matches. – Patrick Artner Nov 18 '17 at 13:39
  • 1
    I think this answer https://stackoverflow.com/a/28745948/7505395 of above mentioned possible duplicate should serve you well. You then can do a `patients = load("G:\patientregister.log")` to get a list of all that patients – Patrick Artner Nov 18 '17 at 13:43

0 Answers0