如何在python中读取一行

use*_*975 8 python file-io

我是Python(2.6)的新手,有一种情况我需要取消读取我刚从文件中读取的一行.这基本上就是我在做什么.

  for line in file:
     print line
     file.seek(-len(line),1)
     zz = file.readline()
     print zz
Run Code Online (Sandbox Code Playgroud)

但是我注意到"zz"和"line"不一样.我哪里错了?

谢谢.

Gus*_*son 12

我不认为for line in file:并且seek做出很好的组合.尝试这样的事情:

while True:
    line = file.readline()
    print line
    file.seek(-len(line),1)
    zz = file.readline()
    print zz

    # Make sure this loop ends somehow
Run Code Online (Sandbox Code Playgroud)

  • `.readline()`在EOF上返回一个空字符串`',因此退出条件是`if not line:break`。 (2认同)