【问题标题】:must be str, not bytes | 'str' has no attribute 'decode'必须是 str,而不是字节 | 'str' 没有属性 'decode'
【发布时间】: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


【解决方案1】:
sys.stdout = codecs.getwriter('utf8')(sys.stdout)

这一行改变了标准输出,所以它做的事情与你通常看到的不同。在 Python 3 中,您实际上不需要关心将内容转换为 utf8,因为一切都已经是 unicode 字符串。

如果您删除该行,编写一个普通字符串(甚至打印一个)应该可以正常工作。

【讨论】:

    猜你喜欢
    • 2018-09-13
    • 1970-01-01
    • 2020-03-29
    • 1970-01-01
    • 1970-01-01
    • 2017-06-07
    • 2016-11-26
    • 2020-12-03
    • 1970-01-01
    相关资源
    最近更新 更多