推荐学习书目
› 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
ThunderEX
V2EX  ›  Python

应该用file.next()还是file.readline()?

  •  
  •   ThunderEX · Mar 18, 2013 · 7402 views
    This topic created in 4942 days ago, the information mentioned may be changed or developed.
    感觉差不多,就是next是raise StopIteration而且有buffer,readline没有buffer而且读到EOF返回''。
    一直以来都是乱用的,现在觉得next可以取代readline()?
    1 replies  •  1970-01-01 08:00:00 +08:00
    linwood
        1
    linwood  
       Mar 20, 2013   ❤️ 1
    如果你把一个file当做一个iterator使用的话,是可以使用使用next()方法的,通常可以放在循环中。会返回下一行或者抛出一个StopIteration异常。

    但是next()和readline()不能混合使用。

    从网上抄了一段代码:
    #!/usr/bin/python

    # Open a file
    fo = open("foo.txt", "r")
    print "Name of the file: ", fo.name

    # Assuming file has following 5 lines
    # This is 1st line
    # This is 2nd line
    # This is 3rd line
    # This is 4th line
    # This is 5th line

    for index in range(5):
    line = fo.next()
    print "Line No %d - %s" % (index, line)

    # Close opend file
    fo.close()

    并且,当时使用for line in file:这种用法的时候实际上就是调用的next方法。

    所以,你在需要使用的readline的时候,可以使用next。但next使用范围更广。
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1261 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 20ms · UTC 23:53 · PVG 07:53 · LAX 16:53 · JFK 19:53
    ♥ Do have faith in what you're doing.