Python:混合文件和循环 [英] Python: Mixing files and loops

查看:212
本文介绍了Python:混合文件和循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个脚本来记录其他程序中的错误,并在遇到错误时重新启动程序。无论什么原因,该程序的开发人员都不觉得有必要将此功能默认放入其程序。



无论如何,程序需要一个输入文件,解析它,并创建一个输出文件。输入文件采用特定格式:



UI - 26474845
TI - 标题(可以是任意行数)
AB - 抽象(也可以是任何行数)



当程序抛出错误时,它会提供跟踪错误所需的参考信息 - 即UI,哪个部分(标题或摘要)以及相对于标题或摘要开头的行号。我想从输入文件中记录违规句子,其中带有参考号和文件的函数,找到句子并记录它。我可以想到的最好的方式是通过文件向前移动特定次数(即n次,其中n是相对于分割开始的行号)。这样做的方法是:

  i = 1 
而i< = lineNumber:
print original.readline()
i + = 1

我不看看这将如何使我失去数据,但Python认为它会,并说ValueError:混合迭代和读取方法将丢失数据。有没有人知道如何正确执行?

解决方案

你得到ValueError,因为你的代码可能有行原始:除了 original.readline()。一个简单的解决方案,解决问题,而不会使程序变慢或消耗更多的内存正在改变原来的行

  b ... 

  while True:
line = original.readline()
如果不是行:break
...
/ pre>

I'm writing a script that logs errors from another program and restarts the program where it left off when it encounters an error. For whatever reasons, the developers of this program didn't feel it necessary to put this functionality into their program by default.

Anyways, the program takes an input file, parses it, and creates an output file. The input file is in a specific format:

UI - 26474845 TI - the title (can be any number of lines) AB - the abstract (can also be any number of lines)

When the program throws an error, it gives you the reference information you need to track the error - namely, the UI, which section (title or abstract), and the line number relative to the beginning of the title or abstract. I want to log the offending sentences from the input file with a function that takes the reference number and the file, finds the sentence, and logs it. The best way I could think of doing it involves moving forward through the file a specific number of times (namely, n times, where n is the line number relative to the beginning of the seciton). The way that seemed to make sense to do this is:

i = 1
while i <= lineNumber:
  print original.readline()
  i += 1 

I don't see how this would make me lose data, but Python thinks it would, and says ValueError: Mixing iteration and read methods would lose data. Does anyone know how to do this properly?

解决方案

You get the ValueError because your code probably has for line in original: in addition to original.readline(). An easy solution which fixes the problem without making your program slower or consume more memory is changing

for line in original:
    ...

to

while True:
    line = original.readline()
    if not line: break
    ...

这篇关于Python:混合文件和循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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