简体   繁体   中英

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?

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.

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

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

or you can use json module:

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

try this:

import json
playlist =  {'playlist': {u'Up in Flames': 0, u'Oceans': 0, u'No Surprises': 0}}
with open('playlist.txt', 'a') as f:
 json.dump(playlist, f)

It will probably work; however it might raise an error about not being able to write to the file. In this case you will have to change the a argument in the open statement, and you can't append only write to the file. Here's something to try to get around the problem:

import json
playlist =  {'playlist': {u'Up in Flames': 0, u'Oceans': 0, u'No Surprises': 0}}
with open('playlist.txt', 'r+') as f:
    playlist = playlist + json.dumps(f)
    json.dump(f, playlist) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM