简体   繁体   English

Python-TypeError:应使用字符缓冲区对象

[英]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: 但看起来像将integers写入文件生成器此错误:

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. 如果希望对象以可读的文本格式存储,则需要某种方式来构造数据,例如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. 还有其他选项,例如xml甚至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. 这是JSON的问题,因为在附加JSON时层次结构也不起作用。 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. 如果您需要添加到现有文件中,则可能需要为存储的文本提供不同的结构,读取退出的文件,将其与新数据合并并重写(Jack Hughes回答)...或者您可以编写一些代码来解析附加的JSON,但是我想这不是标准的重点。

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: 或者您可以使用json模块:

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. 在这种情况下,您将不得不在open语句中更改a参数,并且不能仅追加写入文件。 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) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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