Search code examples
pythondictionarybinarypython-3.4binaryfiles

TypeError: 'dict' does not Support the Buffer Interface


I've looked on stack overflow for an answer, but they all seem to be str or list or int not supported by the buffer interface, whereas my problem is with dict not being supported. What should I do? Can a dictionary not be copied to a .bin binary file? If the solution is complex (or involving modules) could you please explain to me what to do as I am new to programming.

May I also add, I cannot use external modules (i.e. numPy or sciPy) as I am on a work computer without permissions to install modules. I do believe there is a fix to this using the Standard Library, I just don't what what it is.

I am using Python 3.4

#my code
def writeBinary():
    myFile = open('books.bin','wb') #open binary file
    book = {'Title': ' ', #create empty dictionary with keys and no values
            'ISBN': ' ',
            'Price': ' ',
            'Year Of Publication': ' '}
    end = False
    while end != True:
        option = input("Enter 'Y' to enter book details, or 'N' to quit: ")
        if option == 'Y':
            title = input("Enter the title of the book: ") #input data
            book['Title'] = title #assign input data to dictionary keys
            ISBN = input("Enter the ISBN of the book: ")
            book['ISBN'] = ISBN
            price = float(input("Enter the price of the book: £"))
            book['Price'] = price
            yearOfPublication = int(input("Enter the books year of publication: "))
            book['Year Of Publication'] = yearOfPublication
            myFile.write(book) #write dictionary to binary file
            print(book) #to see the current contents of the dictionary
        elif option == 'N':
            print("Input terminated.")
            end = True
        else:
            print("Invalid input. Please try again.")
    myFile.close() #close binary file

writeBinary()  

Solution

  • you cannot write a dictionary on a file like that.

    You have to serialize the dictionary, for instance using json (or pickle):

    import json
    myFile.write(json.dumps(book))
    

    Or directly (myFile must be open in w mode, not wb):

    json.dump(book,myFile)
    

    Then reload it using

    with open('books.bin',"r") as myFile:
        book = json.load(myFile)
    

    json has the advantage over pickle: serialized file can be edited by hand since it's text. But takes more diskspace (unless zipped).