Search code examples
pythonfwrite

Python - TypeError: expected a character buffer object


I'm trying to write this data:

 playlist =  {'playlist': {u'Up in Flames': 0, u'Oceans': 0, u'No Surprises': 0}}

to a file like so:

 with open('playlist.txt', 'a') as f:
     f.write(playlist)

but it looks like writing integers to a file generator this error:

TypeError: expected a character buffer object

how do I correct this? Is there a better file format for my data structure?


Solution

  • You're trying to write a dictionary object to a text file, where as the function is expecting to get some characters to write. If you want your object to be stored in a text format that you can read, you need some way to structure your data, such as JSON.

    import json
    with open('playlist.json', 'w') as f:
        json.dump(playlist, f)
    

    There are other options such as xml or maybe even csv. If you don't care about your data being in a plain text readable format, you could also look at pickling the dictionary object.

    As noted in the comments, your question appended data to a file, rather than writing a new file. This is an issue for JSON as the hierarchical structure doesn't work when its appended too. If you need to add to an existing file you may need to come up with a different structure for your stored text, read the exiting file, combine it with the new data and rewrite it (Jack Hughes answer)... or you could write some code to parse appended JSON, but I guess that's not the point of standards.