This wraps a file handle to allow seeks back to the beginning. It is very useful in Internet work when you need to check that the the input stream is in the proper format before passing it to to the parser.
>>> # Check first if the file starts with 'ERROR:' >>> # and if so, raise an exception >>> import urllib2, ReseekFile >>> >>> infile = urllib2.urlopen("http://somewhere/") >>> infile = ReseekFile(infile) >>> s = infile.readline() >>> if s.startswith("ERROR:"): >>> raise Exception(s[:-1]) >>> infile.seek(0) >>> infile.nobuffer(0) >>> ... proces the input file as normal ..
# 2005-11-06 # Use StringIO if cStringIO doesn't exist. Suggested by Howard Golden # for use with non-CPython implementations. # 2005-05-18 # Can specify a factory to specify how to create the temporary file. # Factories for memory-based (cStringIO) and file-based storages # Track the buffer file size so I don't depend on getvalue() # Fixed a few typos
ReseekFile has been placed in the public domain.
Copyright © 2001-2020 Andrew Dalke Scientific AB