zoukankan      html  css  js  c++  java
  • 转载 python每次读入文件一行的问题(血的教训啊)

     http://blog.csdn.net/oldjwu/article/details/4329401

    Python每次读入文件一行的问题

    分类: Python2009-07-07 21:46 1612人阅读 评论(0) 收藏 举报

      注意到Python每次读入一个文件的一行时,可以有两种写法:

    [python] view plaincopy
    1. f = open("bigFile.txt""r")  
    2. while True:  
    3.     line = f.readline()  
    4.     if line:  
    5.         pass    # do something here  
    6.     else:  
    7.         break  
    8. f.close()  

       另一种写法为:

    [python] view plaincopy
    1. f = open("bigFile.txt""r")  
    2. for line in f:  
    3.     pass    # do something here  
    4. f.close()  

      很明显地,后一种写法更简洁,而且经过测试,效率似乎也略高一些,不过好像很少看见这样的写法。不知道这两种写法有什么区别。



    刚刚看到PyDoc中的FileObject的next()说明
    -----------------------------------------
    next( )

    A file object is its own iterator, for example iter(f) returns f
    (unless f is closed). When a file is used as an iterator, typically in
    a for loop (for example, for line in f: print line), the next() method
    is called repeatedly. This method returns the next input line, or
    raises StopIteration when EOF is hit when the file is open for reading
    (behavior is undefined when the file is open for writing). In order to
    make a for loop the most efficient way of looping over the lines of a
    file (a very common operation), the next() method uses a hidden read-
    ahead buffer. As a consequence of using a read-ahead buffer, combining
    next() with other file methods (like readline()) does not work right.
    However, using seek() to reposition the file to an absolute position
    will flush the read-ahead buffer. New in version 2.3.

  • 相关阅读:
    [BZOJ] 2054 疯狂的馒头
    day33(sql)
    day32(表单校验js和jquery表单校验)
    day31(正则表达式)
    day30(对象转json(java))
    day29(对象转xml(使用java))
    day28(ajax之js原生代码实现)
    day27(反射之内省机制实现BeanUtils)
    day27(反射之内省机制)
    day26(分页查询)
  • 原文地址:https://www.cnblogs.com/finallyliuyu/p/2397763.html
Copyright © 2011-2022 走看看