linwood 最近的时间轴更新
linwood

linwood

V2EX 第 36282 号会员,加入于 2013-03-20 21:10:17 +08:00
19 S 99 B
linwood 最近回复了
2013-03-20 21:41:30 +08:00
回复了 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使用范围更广。
这个应该属于逻辑推理吧,这不就是计算机的弱项么?
关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   5767 人在线   最高记录 6543   ·     Select Language
创意工作者们的社区
World is powered by solitude
VERSION: 3.9.8.5 · 12ms · UTC 01:51 · PVG 09:51 · LAX 18:51 · JFK 21:51
Developed with CodeLauncher
♥ Do have faith in what you're doing.