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
ThunderEX
V2EX  ›  Python

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

  •  
  •   ThunderEX · 2013-03-18 13:56:57 +08:00 · 6157 次点击
    这是一个创建于 4051 天前的主题,其中的信息可能已经有所发展或是发生改变。
    感觉差不多,就是next是raise StopIteration而且有buffer,readline没有buffer而且读到EOF返回''。
    一直以来都是乱用的,现在觉得next可以取代readline()?
    1 条回复    1970-01-01 08:00:00 +08:00
    linwood
        1
    linwood  
       2013-03-20 21:41:30 +08:00   ❤️ 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使用范围更广。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2517 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 15:49 · PVG 23:49 · LAX 08:49 · JFK 11:49
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.