注意到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.
本文探讨了Python中两种不同的文件逐行读取方法:使用while循环配合readline()方法与for循环直接迭代文件对象。通过PyDoc解释了为何后者更为高效,涉及文件迭代器与读取缓冲区的工作原理。
321

被折叠的 条评论
为什么被折叠?



