On 2016-03-15, Steven D'Aprano <st...@pearwood.info> wrote: > Suppose somebody passes me an open file handle. What's the right way to tell > if it is seekable in Python 2? > > I see that stdin has a seek and tell method, but they raise: > > py> sys.stdin.tell() > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > IOError: [Errno 29] Illegal seek > > Are seek and tell guaranteed to exist on all files?
Expecting strict object types isn't really how Python works - while all subclasses of 'file' are guaranteed to have methods called 'seek' and 'tell' (although they're not of course guaranteed to do anything useful), most Python code that says it expects a 'file' doesn't really mean it wants a subclass of 'file', it means it wants something that provides a certain subset of the usual file-like methods. So the answer to your question rather depends on what you mean by "guaranteed to exist" and "all files". Even actual standard 'file' objects, while having 'seek' and 'tell', may well just throw an exception if you try and call those methods as the underlying operating system file handle the object is attached to does not support seeking. > Is there some other way to tell whether the file supports seeking other than > to try it and see? No. > (In Python 3, files have a seekable method.) Yes, but all it is is a wrapper that does try-it-and-see for you. I'd just do something like: try: fileobj.seek(where-i-want-to-seek-to) except (AttributeError, EnvironmentError): # file is not seekable -- https://mail.python.org/mailman/listinfo/python-list