Python:使用f.next()进行迭代时倒退文件中的一行 [英] Python: rewinding one line in file when iterating with f.next()

查看:215
本文介绍了Python:使用f.next()进行迭代时倒退文件中的一行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您使用f.next()遍历文件时,Python的f.tell无法正常工作:

Python's f.tell doesn't work as I expected when you iterate over a file with f.next():

>>> f=open(".bash_profile", "r")
>>> f.tell()
0
>>> f.next()
"alias rm='rm -i'\n"
>>> f.tell()
397
>>> f.next()
"alias cp='cp -i'\n"
>>> f.tell()
397
>>> f.next()
"alias mv='mv -i'\n"
>>> f.tell()
397

看起来它给了您缓冲区的位置,而不是next()的位置.

Looks like it gives you the position of the buffer rather than the position of what you just got with next().

我以前使用过seek/tell

I've previously used the seek/tell trick to rewind one line when iterating over a file with readline(). Is there a way to rewind one line when using next()?

推荐答案

否.我将创建一个适配器,该适配器在很大程度上转发所有呼叫,但在执行next时保留最后一行的副本,然后让您调用其他方法以使该行再次弹出.

No. I would make an adapter that largely forwarded all calls, but kept a copy of the last line when you did next and then let you call a different method to make that line pop out again.

实际上,我将适配器做成可以包装任何可迭代对象的适配器,而不是文件包装器,因为这听起来像在其他情况下经常有用.

I would actually make the adapter be an adapter that could wrap any iterable instead of a wrapper for file because that sounds like it would be frequently useful in other contexts.

Alex建议使用itertools.tee适配器也可以,但是我认为编写自己的迭代器适配器来处理这种情况通常会更干净.

Alex's suggestion of using the itertools.tee adapter also works, but I think writing your own iterator adapter to handle this case in general would be cleaner.

这里是一个例子:

class rewindable_iterator(object):
    not_started = object()

    def __init__(self, iterator):
        self._iter = iter(iterator)
        self._use_save = False
        self._save = self.not_started

    def __iter__(self):
        return self

    def next(self):
        if self._use_save:
            self._use_save = False
        else:
            self._save = self._iter.next()
        return self._save

    def backup(self):
        if self._use_save:
            raise RuntimeError("Tried to backup more than one step.")
        elif self._save is self.not_started:
            raise RuntimeError("Can't backup past the beginning.")
        self._use_save = True


fiter = rewindable_iterator(file('file.txt', 'r'))
for line in fiter:
    result = process_line(line)
    if result is DoOver:
        fiter.backup()

将其扩展到一个可以备份多个值的地方并不难.

This wouldn't be too hard to extend into something that allowed you to backup by more than just one value.

这篇关于Python:使用f.next()进行迭代时倒退文件中的一行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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