Alternative to os.listdir()/os.stat()

Donn Cave donn at drizzle.com
Thu Jan 23 02:35:20 EST 2003


Quoth "Alfredo P. Ricafort" <alpot at mylinuxsite.com>:
| I'm trying to get the files under a directory and its details. What  I
| did is to call os.listdir() and then os.stat(). So my code looks
| something like this:
|
|
|     fileList=os.listdir(path)
|     for i in range(len(fileList)):
|         f=os.stat(path+'/'+j)
|
| However, I noticed that this approach takes a long time when the
| directory contains lots of files. So what I am looking for now is a
| function that can give me the details is one go, much like 'ls -ltra' in
| UNIX. 
|
| Does one exists?

Nope!  I think more specifically what would work here is if listdir()
were to return the inode as well as the name of each file, and if there
were some way to stat a file by inode rather than name.  This would
eliminate 1 directory read per file.  However, neither of those conditions
are met here - listdir() doesn't return the inode, and anyway you couldn't
use it.

You can probably get some modest improvement in execution time, if you
chdir(path) first, and then stat(j).  The way you write it causes parent
directories to be read once for every file too.

	Donn Cave, donn at drizzle.com




More information about the Python-list mailing list