getting file size

John Machin sjmachin at lexicon.net
Fri Jan 21 23:59:39 EST 2005


Bob Smith wrote:
> Are these the same:
>
> 1. f_size = os.path.getsize(file_name)
>
> 2. fp1 = file(file_name, 'r')
>     data = fp1.readlines()
>     last_byte = fp1.tell()
>
> I always get the same value when doing 1. or 2. Is there a reason I
> should do both? When reading to the end of a file, won't tell() be
just
> as accurate as os.path.getsize()?
>

Read the docs. Note the hint that you get what the stdio serves up.
ftell() can only be _guaranteed_ to give you a magic cookie that you
may later use with fseek(magic_cookie) to return to the same place in a
more reliable manner than with Hansel & Gretel's non-magic
bread-crumbs. On 99.99% of modern filesystems, the cookie obtained by
ftell() when positioned at EOF is in fact the size in bytes. But why
chance it? os.path.getsize does as its name suggests; why not use it,
instead of a method with a side-effect? As for doing _both_, why would
you??




More information about the Python-list mailing list