繁体   English   中英

Python,如何一次又一次读取同一文件时将枚举的迭代器设置为0

[英]Python, how can I set iterator of enumerate to 0 while reading same file again and again

with open("...txt") as fp: 
    for i, line in enumerate(fp): 
        if some condition : 
            i=0
            fp.seek(0)

文本很大,数据的GB数很大,所以我使用枚举。 我需要处理这个巨大的文件数千次,所以为了提高效率,我决定第一次打开它。 但是,尽管此代码有效,但i并没有变为0,而是继续递增。 我需要将其设为零,因为我需要第i行的位置。 每次乘以数十亿*几千并进行一些模运算只是效率低下。

所以我的问题是,当我回到文件开头时,如何将i设置为零? 在此先感谢(我使用python 3.6)

你总是可以使自己的复位枚举,但有可能是更好的方法做你真正想做的事情。

尽管如此,这还是一个可重置的枚举器的样子:

 def reset_enumerate(thing, start=0):
     x = start
     for t in thing:
         val = yield t, x
         if val is not None:
             x = val
         else:
             x += 1

然后,您将像这样使用它:

r = reset_enumerate(range(10))
for i, num in r:
    print('i:', i, 'num:', num)     
    if i == 5:
        i, num = r.send(0)
        print('i:', i, 'num:', num)

这是一个如何模拟类似场景的示例:

假设我有一个名为input.txt的文件,其中包含这种数据:

1
2
3

码:

j = 0
with open('input.txt', 'r') as f:
    for k in f:
        # A break condition
        # If not we'll face an infinite loop
        if j > 4:
            break
        if k.strip() == '2':
            f.seek(0)
            print("Return to position 0")
            # Don't forget to increment j 
            # Otherwise, we'll end up with an infinite loop
            j += 1
        print(k.strip())

将输出:

1
Return to position 0
2
1
Return to position 0
2
1
Return to position 0
2
1
Return to position 0
2
1
Return to position 0
2

如评论中所述, enumerate是一个生成器函数。 完成时已经“精疲力尽”。 这也是为什么您不能仅仅“重置”它的原因。 这是列举的PEP ,以进一步解释其工作原理。

此外,正如评论中指出的那样, 这篇文章提供了处理大型文件的典型方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM