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

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

 

 

   另一种写法为:

 

 

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

 



刚刚看到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.

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值