Frage

I'm writing a program that opens a database file saved with pickle. but if i want to load the list from the file into the memory with StringIO/cStringIO it says:

Opening database...
Loading database into memory...
Traceback (most recent call last):
...
  File "C:\myfile.py", line 17 in open_database
    database.write(databasefile)
TypeError: must be string or read-only character buffer, not list

This is my code:

def open_database(self):
    print("Opening database...")
    databasefile = open('database.dat', "r")
    databasecontent = cPickle.load(databasefile)
    databasefile.close()
    print('Loading database into memory...')
    database = cStringIO.StringIO()
    database.write(databasecontent)
    atexit.register(close_database)
War es hilfreich?

Lösung

It is already in memory. Loading a pickle returns a python structure.

Moreover, a StringIO object is a in-memory file-like object, not a Python object structure. You cannot take the in-memory representation of a python structure and 'write' it into memory, you instruct the Python interpreter to construct those objects for you (which is what the pickle module does for you).

Last but not least, you really should avoid using atexit to close files. File objects that are still open when Python exits are automatically closed. Even if Python doesn't this for some reason, the OS would do it anyway.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top