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

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

问题描述

我正在编写一个脚本,该脚本记录另一个程序的错误,并在遇到错误时从中断的地方重新启动该程序.无论出于何种原因,该程序的开发人员都没有必要默认将此功能放入其程序中.

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)

程序抛出错误时,它会为您提供跟踪错误所需的参考信息-即UI,哪个部分(标题或摘要)以及相对于标题或摘要开头的行号.我想使用输入参考编号和文件,查找句子并将其记录的函数记录输入文件中令人讨厌的句子.我想到的最好方法是在文件中向前移动特定的次数(即n次,其中n是相对于开始部分的行号).这样做似乎很有意义:

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

我不知道这怎么会使我丢失数据,但是Python认为会这样,并说ValueError: Mixing iteration and read methods would lose data.有人知道如何正确执行此操作吗?

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?

推荐答案

您会收到ValueError,因为您的代码除了original.readline()之外还可能还有for line in original:.可以在不降低程序速度或消耗更多内存的情况下解决此问题的简单解决方案,

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:
    ...

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

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

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