获取文件中的下一行 [英] Getting next line in a file

查看:92
本文介绍了获取文件中的下一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读一个文件,想知道是否有办法读取for循环中的下一行?



我正在读取这样的文件:

  file = open(input,r)。read()
for file.splitlines()
line = doSomething()

所以无论如何我都可以检索下一行文件中的for循环,使我可以在 doSomething()函数中执行一些操作?




解决方案

只要循环打开文件即可:

  infile = open(input,r)
在infile中的行:
line = doSomething(line,next(infile))
/ pre>

因为您现在使用该文件作为迭代器,所以您可以调用 infile 随时可以检索一个额外的行。



另外两个提示:


  1. 不要调用变量文件;它掩盖了python中内置的文件类型对象。我将它命名为 infile

  2. code>与语句。它会在完成时自动关闭文件:

     与开放(输入,r)作为infile:
    为infile行:
    line = doSomething(line,next(infile))



      I am reading in a file and wonder if there's a way to read the next line in a for loop?

      I am currently reading the file like this:

      file = open(input,"r").read()
      for line in file.splitlines():
        line = doSomething()
      

      So is there anyway I can retrieve the next line of the file in that for loop such that I can perform some operation in the doSomething() function?

      Thanks

      解决方案

      Just loop over the open file:

      infile = open(input,"r")
      for line in infile:
          line = doSomething(line, next(infile))
      

      Because you now use the file as an iterator, you can call the next() function on the infile variable at any time to retrieve an extra line.

      Two extra tips:

      1. Don't call your variable file; it masks the built-in file type object in python. I named it infile instead.

      2. You can use the open file as a context manager with the with statement. It'll close the file for you automatically when done:

        with open(input,"r") as infile:
            for line in infile:
                line = doSomething(line, next(infile))
        

      这篇关于获取文件中的下一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆