【发布时间】:2016-07-02 09:20:02
【问题描述】:
我有这个从 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,而不是 bytes
而且,它不像在打印任何东西,所以,它一定是在第一个键时失败了?但是......第一个键既不是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
【问题讨论】:
-
您使用的是 Python 3.x。字符串没有
decode方法。如果您需要字符串中的字节对象,那么encode应该可以。 -
可能有一些字节和一些 str 键。你可以试试
print(list(document.keys())看看有什么键。 -
由于您使用的是
sys.stdout.write,请考虑在之后添加sys.stdout.flush(),以便立即更新输出。这样你就可以判断你的两次运行(有和没有解码)是否产生不同数量的密钥(他们可能这样做)。 -
@poke 查看编辑中的新数据....可能是因为我必须通过 python3 的参数调用它吗?因为,它甚至没有打印那个 1,而且我有一个从 mysql 中提取的类似脚本,它没有给出这样的错误,但是使用 python 2.7
-
哦,我完全错过了
sys.stdout = codecs.getwriter('utf8')(sys.stdout)行。你应该删除它。
标签: python string mongodb python-3.x