ajj
ajj

Reputation: 101

os.walk not parsing a few directories

I am kinda new to python and right now I am trying out some stuff, specifically : recurse through all the directories and files and print the file sizes using os.walk.

My problem is, that the program does not recurse through a few directories although files are present in those directories. An example in my machine would be the directory Python2.7. This is inside the /usr directory. When I give the top path as /usr, this directory is not parsed. But when I specifically mention the path to Python2.7 directory, then it does parse through it. Can anyone help me out by pointing what is wrong ? Here is my code :

from os import walk, listdir, stat
from os.path import join, isdir, isfile, islink, getsize, abspath, dirname, realpath
from stat import ST_INO as st_ino
from sets import Set


def determine_parent_directory( root ):
     #print "parent-dirname : ", dirname( realpath( root ) )
     return stat( dirname( abspath( root ) ) ).st_ino

def determine_size( root, file ):
    size_type = ""
    file_size = getsize( abspath( ( join( root, file ) ) ) ) 
    if file_size < 1024:
        size_type = "bytes"
    else:
    if file_size > 1024:
        file_size /= 1024                  
        size_type = "Kb"
    if file_size > 1024:
        file_size /= 1024
        size_type = "Mb"
    if file_size > 1024:
        file_size /= 1024
        size_type = "Gb"
    if file_size > 1024:
        file_size /= 1024
        size_type = "Tb"

    return [file_size, size_type]

def walk_through( path ):
    total_size = 0
    for root, dirs, files in walk( path ):
        print root.split( "/" )[-1]
        print "\n"

        for file in files:
            if islink( abspath( join( root, file ) ) ):
                print "link"
                continue
            #total_size += determine_size( root, file )[0]
            file_size, size_type = determine_size( root, file )
            print "\t\t\t{0} -- {1} {2}".format ( file, file_size, size_type )
            #total_size += file_size
    print "\n" 
    #print total_size

def get_path_user():
    default_path = "/usr"
    walk_through( default_path )

if __name__ == '__main__':
    get_path_user()

Upvotes: 0

Views: 281

Answers (2)

yak
yak

Reputation: 9041

Is it a symbolic link?

os.walk(top[, topdown=True[, onerror=None[, followlinks=False]]])

By default, walk() will not walk down into symbolic links that resolve to directories. Set followlinks to True to visit directories pointed to by symlinks, on systems that support them.

Note: Be aware that setting followlinks to True can lead to infinite recursion if a link points to a parent directory of itself. walk() does not keep track of the directories it visited already.

Upvotes: 1

Andrew Hare
Andrew Hare

Reputation: 351516

Check the permissions on those directories - does the user account that the script is running under have rights to those directories?

Upvotes: 0

Related Questions