推荐学习书目
› Learn Python the Hard Way
Python Sites
› PyPI - Python Package Index
› http://diveintopython.org/toc/index.html
› Pocoo
值得关注的项目
› PyPy
› Celery
› Jinja2
› Read the Docs
› gevent
› pyenv
› virtualenv
› Stackless Python
› Beautiful Soup
› 结巴中文分词
› Green Unicorn
› Sentry
› Shovel
› Pyflakes
› pytest
Python 编程
› pep8 Checker
Styles
› PEP 8
› Google Python Style Guide
› Code Style from The Hitchhiker's Guide
okface
V2EX  ›  Python

TypeError: a bytes-like object is required, not 'str'

  •  
  •   okface · Feb 22, 2018 · 4030 views
    This topic created in 3175 days ago, the information mentioned may be changed or developed.



    在 python3 中报错时为啥呀,新手一枚~
    ynyounuo
    ynyounuo
    Feb 22, 2018❤️1
    1
    okface
    okface
    OP
    Feb 22, 2018
    2
    @ynyounuo 是我没说清楚,问题是我记得我之前一直都是这么写的啊。我要写成 filename.decod('utf-8')这种吗?
    monsterxx03
    monsterxx03
    Feb 22, 2018
    3
    1. 统计行数你这写法太繁琐了, open return 的 file 对象可以直接遍历: sum(1 for _ in open(filename))
    2. open(filename, 'rb') 是用二进制模式打开,读出来的是 bytes, 你传入的 eol 是 str, 改成用文本 'r' 模式打开
    ipwx
    ipwx
    Feb 22, 2018❤️1
    4
    import codecs

    with codecs.open(filename, 'rb', 'utf-8') as f
    ipwx
    ipwx
    Feb 22, 2018
    5
    @monsterxx03 看他的参数 eol='\n',可以自定义的。
    snoopygao
    snoopygao
    Feb 22, 2018
    6
    论坛的头像规则里说:如果你是男人,请不要用女人的照片做头像,以免误导其他会员
    monsterxx03
    monsterxx03
    Feb 22, 2018
    7
    @ipwx 要看他真正需求,如果就是统计行数完全不需要自定义换行符,windows/linux python 都能 handle 的,否则这个问题不叫统计行数
    okface
    okface
    OP
    Feb 22, 2018
    8
    @ipwx thank you ,感谢 10 铜币~
    wellsc
    wellsc
    Feb 22, 2018
    9
    我以为是真人
    okface
    okface
    OP
    Feb 22, 2018
    10
    @monsterxx03 学习了,这个方法我直接 copy 的,所以没有深究 python 能不能识别\n 和\r\n
    okface
    okface
    OP
    Feb 22, 2018
    11
    @snoopygao 喜欢陈意涵而已。。。哈哈
    ycz0926
    ycz0926
    Feb 22, 2018
    12
    1、b"abcdddd"
    2、"sdddd".encode('utf-8')
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1517 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 23:16 · PVG 07:16 · LAX 15:16 · JFK 18:16
    ♥ Do have faith in what you're doing.