linwood's recent timeline updates
linwood

linwood

V2EX member #36282, joined on 2013-03-20 21:10:17 +08:00
19 S 99 B
linwood's recent replies
Mar 20, 2013
Replied to a topic by ThunderEX Python 应该用file.next()还是file.readline()?
如果你把一个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   ·   Solana   ·   3220 Online   Highest 6679   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 17ms · UTC 12:55 · PVG 20:55 · LAX 05:55 · JFK 08:55
♥ Do have faith in what you're doing.