您在这里遇到问题有两个原因。第一个是您
fo以只写模式创建的。您需要一个可以读写的文件对象。您还可以使用
with关键字在完成处理后自动销毁文件对象,而不必担心手动关闭它:
# the plus sign means "and write also"with open("foo.txt", "r+") as fo: # do write operations here # do read operations here第二个是(就像您非常强烈地指出的错误一样)文件对象
fo(文本文件对象)没有
next方法。您正在使用针对Python
2.x编写的教程,但您正在使用Python3.x。这对您来说并不顺利。(我相信
nextwas /也许在Python
2.x中有效,但在3.x中无效。)相反,与
nextPython 3.x最类似的是
readline,如下所示:
for index in range(7): line = fo.readline() print("Line No %d - %s % (index, line) + "n")请注意,这仅在文件至少有7行时有效。否则,您将遇到异常。一个遍历文本文件的更安全,更简单的方法是使用for循环:
index = 0for line in file: print("Line No %d - %s % (index, line) + "n") index += 1或者,如果您想获得更多的pythonic,可以使用enumerate函数:
for index, line in enumerate(file): print("Line No %d - %s % (index, line) + "n")


