How to get the size of a file?

David M. Cooke cookedm+news at physics.mcmaster.ca
Sun Oct 17 00:18:41 EDT 2004


User <1 at 2.3> writes:

> Anyone have ideas which os command could be used to get the size of a
> file without actually opening it?  My intention is to write a script
> that identifies duplicate files with different names.  I have no
> trouble getting the names of all the files in the directory using the
> os.listdir() command, but that doesn't return the file size.  In order
> to be identical, files must be the same size, so I want to use file
> size as the first criteria, then, if they are the same size, actually
> open them up and compare the contents.  
>
> I have written such a script in the past, but had to resort to
> something like:
>
> os.system('dir *.* >> trash.txt')

You're looking for os.stat. It returns an object whose attributes have
info about the file.

>>> import os
>>> s = os.stat('somefile')
>>> print s.st_size
2821
(or whatever)

More info in the docs for the os module, of course.

-- 
|>|\/|<
/--------------------------------------------------------------------------\
|David M. Cooke
|cookedm(at)physics(dot)mcmaster(dot)ca



More information about the Python-list mailing list