file size 'mystery'

george young gry at ll.mit.edu
Tue May 20 11:19:41 EDT 2003


On Tue, 20 May 2003 16:26:38 +0200
Sven Brandt <sven_NOSPAM at manastar.de> threw this fish to the penguins:
> I'd like to determin the size of a file an do stuff at a certain size 
> (here > 0 byte). In Python:
> 
>    my_file=open(some_file)      # some_file has size of 1000 byte
> 
>    print len(my_file.read())    # prints 1000
>    x=len(my_file.read())
> 
>    if len(my_file.read()) > 0:
>      print len(my_file.read())  # prints 0
> 
>    return printed
...
If you're just looking for file size, it's much more efficient
to do a 'stat', e.g.:

% ls -l .bashrc
-rw-r--r--    1 gry      users        2371 Jan 29 15:21 .bashrc
% python
>>> import os
>>> s=os.stat('.bashrc')
>>> s.st_size
2371L
>>>

See: http://www.python.org/doc/current/lib/os-file-dir.html

Have fun,
-- George




More information about the Python-list mailing list