TypeError:期望Python中的字符缓冲区对象

时间:2015-10-30 01:09:38

标签: python file buffer typeerror

我不知道为什么我不能将此 a b c d e f a 0 1 0 1 0 1 b 0 0 1 0 1 1 c 1 0 0 1 0 1 d 1 1 0 0 0 1 e 1 0 1 0 0 1 f 1 0 1 1 0 0 写入档案:

document

这是写入文件的代码:

document=['', 'feeling frisky cool cat hits join us', 'askjoe app add music videos free today saintkittsandnevis', 'give dog flea bath midnight greeeeat smells like dawn', 'cat finds flash drive spent weeks looking', 'downside cat dude means can recognize nice smell pee second', 'louis pine apple make life brighter like star please follow me', 'gonna need nice cup coffee morning', 'gonna need nice cup coffee morning', 'iphone gives warning dies smh']

这是我得到的错误:

with open("cleaned_tweet.txt", "w") as cleaned_tweet_file:
    cleaned_tweet_file.write(document)

2 个答案:

答案 0 :(得分:3)

方法write()str作为参数,而不是list对象。这是TypeError的原因,并在str()调用中将其包裹起来,只需为您提供 list对象documents和<的字符串表示形式em>不是列表中的文件本身。

使用:

with open("cleaned_tweet.txt", "w") as cleaned_tweet_file:
    cleaned_tweet_file.write(str(document))

您将list对象作为字符串写入您的文件,因此需要大量的字符串:

"['', 'feeling frisky cool cat hits join us', 'askjoe app add music videos free today saintkittsandnevis', 'give dog flea bath midnight greeeeat smells like dawn', 'cat finds flash drive spent weeks looking', 'downside cat dude means can recognize nice smell pee second', 'louis pine apple make life brighter like star please follow me', 'gonna need nice cup coffee morning', 'gonna need nice cup coffee morning', 'iphone gives warning dies smh']"

将出席。逻辑上不是你想要的。

您可以使用与list字符串一起使用的file.writelines(),也可以使用str转换为list,而不是file.write()转换为for。 {1}}与writelines()循环结合使用:

使用with open("cleaned_tweet.txt", "w") as cleaned_tweet_file: cleaned_tweet_file.writelines(document)

write

此处无需循环或手动转换。

使用for和简单的with open("cleaned_tweet.txt", "w") as cleaned_tweet_file: for tweet in document: cleaned_tweet_file.write(tweet) 循环:

cleaned_tweet_file.write("Tweet: " + tweet + "\n")

这具有相同的确切效果。它的主要优点是它允许您指定每行的附加内容;如果您需要为每条推文和前缀添加换行​​符,请明确添加function calcPD(){ var pound = document.getElementById("field1").value; var calc = quilos / 2.2046; var resul = document.getElementById("pound").value=calcularr.toFixed(2); } function calcKg(){ var kg = document.getElementById("field1").value; var calc = quilo * 2.2046; var resul = document.getElementById("pound").value=calcular.toFixed(2); } funcion invert(){ ??? }

答案 1 :(得分:1)

以下是解决方案,添加str

with open("cleaned_tweet.txt", "w") as cleaned_tweet_file:
    cleaned_tweet_file.write(str(document))