Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中读取文件中的行时迭代同一行_Python_File_Loops - Fatal编程技术网

在python中读取文件中的行时迭代同一行

在python中读取文件中的行时迭代同一行,python,file,loops,Python,File,Loops,我正在读取文件的每一行并对其执行一些操作。有时,由于网络中的某些奇怪行为,程序会抛出一个错误。它对远程计算机执行SSH。这种情况偶尔发生一次。我希望捕获此错误,并在同一行上再次执行相同的操作。具体地说,我想再读一遍同一行。我在找这样的东西 with open (file_name) as f: for line in f: try: do this except IndexError:

我正在读取文件的每一行并对其执行一些操作。有时,由于网络中的某些奇怪行为,程序会抛出一个错误。它对远程计算机执行SSH。这种情况偶尔发生一次。我希望捕获此错误,并在同一行上再次执行相同的操作。具体地说,我想再读一遍同一行。我在找这样的东西

with open (file_name) as f:  
    for line in f:  
        try:    
            do this  
        except IndexError:  
            go back and read the same line again from the file.  

只要您在for循环的块内,您仍然可以访问该行,当然,除非您在知情的情况下修改它。因此,您实际上不需要从文件中重新读取它,但它仍保留在内存中

例如,您可以反复尝试“执行此操作”,直到成功,如下所示:

for line in f:
    while True:
        try:
            print(line)
            doThis()
        except IndexError:
            # we got an error, so let’s rerun this inner while loop
            pass
        else:
            # if we don’t get an error, abort the inner while loop
            # to get to the next line
            break

你不需要重读这句话。line变量保留您的行。如果操作失败,您要做的是重试操作。一种方法是使用函数,并在函数失败时从该函数调用该函数

def do(line):
    try:
        pass # your "do this" code here
    except IndexError:
        do(line)

with open (file_name) as f:  
    for line in f:  
        do(line) 

Python没有将执行指针重置为当前迭代开始的“repeat”关键字。最好的方法可能是再次查看代码的结构,并将“执行此操作”分解为一个函数,该函数将重试,直到完成为止

但是,如果您真的开始尽可能地模拟repeat关键字,我们可以通过将file对象包装到生成器中来实现这一点

不要直接在文件上循环,而是定义一个生成器,使用repeat选项一次生成一行文件

def repeating_generator(iterator_in):
    for x in iterator_in:
        repeat = True
        while repeat:
            repeat = yield x
            yield
可以使用此生成器包装文件对象。我们将一个标志传递回生成器,告诉它是重复上一行还是继续下一行

with open (file_name) as f:
    r = repeating_generator(f)  
    for line in r:  
        try:    
            #do this
            r.send(False) # Don't repeat
        except IndexError:  
            r.send(True) #go back and read the same line again from the file.  

看看这里发生了什么。我不认为这是最可读的方式,先考虑替代方案!请注意,您需要Python2.7或更高版本才能使用它

为什么您认为需要重新读取该行?我的程序由于从网络接收到一些奇怪的输出而抛出索引错误。这种情况偶尔发生一次。可能是十分之一。我认为如果我可以为同一行再次运行程序,这个问题就可以解决。你已经有了这一行,只需重新使用相同的值。我在文件上循环,而不是存储这些行。就像“continue”命令跳过一个迭代一样,我正在寻找一个重复相同迭代的命令。非常感谢您的及时回复。嗨,詹姆斯,非常感谢您的回复。我一定能实现这一点来解决我的问题!你只是没有给我提供解决方案,但当你说Python没有“repeat”关键字将执行指针重置为当前迭代的开始时,你确实启发了我。不客气。看起来你是新来的。如果你觉得答案有帮助,你应该投票给他们,并接受你认为最有帮助的答案。是的,你是对的。这是我的第一个问题。我仍然没有足够的声誉来支持你的解决方案。抱歉