Is reverse reading possible?
Anthony Liu
antonyliu2002 at yahoo.com
Sun Mar 14 14:10:47 EST 2004
Jeff and Ivo,
Thank you very much for your solution. Yes, I figure
out it is easy for an ascii text.
The files (nearly 4M each)I am gonna read are a
mixture of Chinese and English, where each Chinese
character has 2 bytes and each English (ASCII) has 1
byte, although the majority of the texts is Chinese.
So, if we reverse-read it without taking into
consideration the 2-byte Chinese characters, we are
gonna get the Chinese characters spelled out in the
wrong way - unreadable!
So, it might be tedious to read such a text reversely
unless you have a smarter idea. Do you?
--- Jeff Epler <jepler at unpythonic.net> wrote:
> on seekable, byte-oriented binary files, sure.
>
> import errno
>
> SEEK_SET, SEEK_CUR, SEEK_END = range(3)
>
> class Reversed:
> def __init__(self, f):
> self.f = f
> self.f.seek(-1, SEEK_END)
> self.at_eof = 0
>
> def read_byte(self):
> if self.at_eof: return ''
> byte = self.f.read(1)
> try:
> self.f.seek(-2, SEEK_CUR)
> except IOError, detail:
> if detail.errno == errno.EINVAL:
> self.at_eof = 1
> else:
> raise
> return byte
>
> def __iter__(self): return self
>
> def next(self):
> r = self.read_byte()
> if r == '': raise StopIteration
> return r
>
> >>> "".join(Reversed(file("/etc/redhat-release",
> "rb")))
> '\n)worraY( 1 esaeler eroC arodeF'
>
> Jeff
__________________________________
Do you Yahoo!?
Yahoo! Mail - More reliable, more storage, less spam
http://mail.yahoo.com
More information about the Python-list
mailing list