finding file size

David M. Wilson dw-google.com at botanicus.net
Fri Jan 2 01:46:12 EST 2004


"Sean Ross" <sross at connectmail.carleton.ca> wrote...

> My question is this: Is there a reason why file objects could not have a
> size method or property? So that you could then just ask the file how big it
> is using fd.size or fd.size(). I'm just curious, because, well, it seems to
> have obvious utility, and the way to find it is less than obvious (at least,
> it was to me).

Hey!

1) Using 'fd' as a name for a file object is a bad idea - you can get
fds from os.open. If you insist on C-ish names, how about 'fp'
instead? :)

2) There's nothing to stop the file object from having a size method,
except that file-like objects then have more to implement.

How about something like:

py> class SizedFile(file):
...     def __len__(self):
...             oldpos = self.tell()
...             self.seek(0, 2)
...             length = self.tell()
...             self.seek(oldpos)
...             return length
... 
py> bleh = SizedFile("/etc/passwd")
py> len(bleh)
1520
py> len([ x for x in bleh ])
33



As I wrote this I realised it's wrong - size() would be better, since
the length of the sequence is not the number of bytes. Maybe it is in
binary mode? Dunno, me sleepy, goodnight..


David.


> 
> Thanks,
> Sean



More information about the Python-list mailing list