![](/img/trans.png)
[英]'str' object has no attribute 'decode' & "write() argument must be str, not bytes"
[英]must be str, not bytes | 'str' has no attribute 'decode'
我有以下简单代码可从mongo数据库中提取:
import sys
import codecs
import datetime
from pymongo import MongoClient
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
mongo_db = "database"
collectionId = "coll name"
def main(argv):
client = MongoClient("mongodb://localhost:27017")
db = client[mongo_db]
collection = db[collectionId]
cursor = collection.find({})
for document in cursor:
# if "content" in document:
# sys.stdout.write(
# "|"+(document['content'] if document['content'] is not None else "")+"\n")
for key, value in document.items() :
sys.stdout.write(key.decode('utf-8'))
if __name__ == "__main__":
main(sys.argv)
这样运行,让我
AttributeError:“ str”对象没有属性“ decode”
那么...这是一个str对象,然后呢? 但是如果我删除解码,我得到
TypeError:必须为str,而不是字节
而且,它不像在打印任何东西,因此,它一定是在第一个键上失败了吗? 但是...第一个键既不是str也不是字节??? 我该如何打印?
编辑刷新测试:
for key, value in document.items() :
sys.stdout.write("1")
sys.stdout.flush()
sys.stdout.write(key.decode('utf-8'))
sys.stdout.flush()
我将for更改为该错误
~/Desktop$ python3 sentimongo.py
Traceback (most recent call last):
File "sentimongo.py", line 30, in <module>
main(sys.argv)
File "sentimongo.py", line 24, in main
sys.stdout.write("1")
File "/usr/lib/python3.4/codecs.py", line 374, in write
self.stream.write(data)
TypeError: must be str, not bytes
sys.stdout = codecs.getwriter('utf8')(sys.stdout)
该行更改了标准输出,因此它执行的功能与您通常看到的不同。 在Python 3中,您真的不需要关心将事物转换为utf8的情况,因为所有内容已经都是unicode字符串。
如果删除该行,则编写一个普通的字符串(甚至打印一个字符串)应该可以正常工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.