viernes, 6 de noviembre de 2015

[Easy trick] Examine an entire directory tree using python

[Easy trick] How to easily analyze an entire directory tree: os.walk

Today we are going to talk about a small problem you sometimes have to deal with: evaluating an entire directory tree in order to find some types of files. Say that the user is manually leaving these files at random places (very typical), that you want to make sure you are not missing a particular file or that you want to know some folders size (sometimes Linux does not show you the size of a folder but the size of a the file representing the folder (4096 bytes), therefore creating a script to evaluate what is the bigger folder in, for instance, a project directory tree is quite straightforward).
The "os" python library has a very nice method called "walk" that will return an iterator you can use to obtain all files names.
We should provide os.walk() with a string indicating what folder we want to "walk" trough.


This option for instance will provide us with an iterator with all the subdirectories from /.

You can even obtain folder, files and the folder names that being evaluated (root)



This is an easy trick that is very useful for many applications.

If you want to go downto a particular subdirectory you should recurrent calls of this method.

No hay comentarios:

Publicar un comentario