So forgive me if this is a stupid question, but why can't I get the
size of a file by doing a len(file)?
Charles Burns' answer makes a good point about Unix's "everything is a file" philosophy, and, although you always can use os.fstat()
to get the 'size' for any file descriptor, with something like...
import os
f = open(anything)
size = os.fstat(f.fileno()).st_size
...it may not return anything meaningful or useful...
>>> os.fstat(sys.stdout.fileno()).st_size
0
>>> fd1, fd2 = os.pipe()
>>> os.fstat(fd1).st_size
0
I think the reason is that a Python file object, or file-like object, is supposed to represent a stream, and streams don't inherently have a length, especially if they're write-only, like sys.stdout
.
Usually, the only thing you can guarantee about a Python file-like object is that it will support at least one of read()
or write()
, and that's about it.