V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2018-02-22 13:51:39 +08:00 · 3133 次点击
    这是一个创建于 2226 天前的主题,其中的信息可能已经有所发展或是发生改变。



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

    with codecs.open(filename, 'rb', 'utf-8') as f
    ipwx
        5
    ipwx  
       2018-02-22 14:12:45 +08:00
    @monsterxx03 看他的参数 eol='\n',可以自定义的。
    snoopygao
        6
    snoopygao  
       2018-02-22 14:15:34 +08:00
    论坛的头像规则里说:如果你是男人,请不要用女人的照片做头像,以免误导其他会员
    monsterxx03
        7
    monsterxx03  
       2018-02-22 14:15:36 +08:00
    @ipwx 要看他真正需求,如果就是统计行数完全不需要自定义换行符,windows/linux python 都能 handle 的,否则这个问题不叫统计行数
    okface
        8
    okface  
    OP
       2018-02-22 14:20:20 +08:00
    @ipwx thank you ,感谢 10 铜币~
    wellsc
        9
    wellsc  
       2018-02-22 14:20:39 +08:00
    我以为是真人
    okface
        10
    okface  
    OP
       2018-02-22 14:21:59 +08:00
    @monsterxx03 学习了,这个方法我直接 copy 的,所以没有深究 python 能不能识别\n 和\r\n
    okface
        11
    okface  
    OP
       2018-02-22 14:22:30 +08:00
    @snoopygao 喜欢陈意涵而已。。。哈哈
    ycz0926
        12
    ycz0926  
       2018-02-22 14:22:37 +08:00
    1、b"abcdddd"
    2、"sdddd".encode('utf-8')
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1051 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 19:10 · PVG 03:10 · LAX 12:10 · JFK 15:10
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.