akshay
akshay

Reputation: 3

how to get list of files on windows which have file size less than say 500mb?

This is python script is what I came up with so far. I just wanted a list of directories along with files of sizes greater than 500mb, the built-in os.walk() returns a list of subdirectories too. So, I tweaked that by referring to this post.

    import os
    import sys,getopt
    def do_stuff(path):
        def walk_free(top,topdown=True,onerror=None,followlinks=False):
            islink,isdir,join=os.path.islink,os.path.isdir,os.path.join
            try:
             names=os.listdir(top)
            except Exception as e:
                   print e
                   return 
            dirs,nondirs=[],[]
            for name in names:
                if isdir(join(top,name)):
                   dirs.append(name)
                else:
                  nondirs.append(name)
            if topdown:
               yield top,nondirs
            for name in dirs:
                new_path=join(top,name)
                if followlinks or not islink(new_path):
                   for x in walk_free(new_path,topdown,onerror,followlinks):
                   yield x
            if not topdown:
               yield top,nondirs
    with open("delete.txt",'a+') as output:
    output.write(" PATH |  FILE \n")
    for direc,files in walk_free(path):
        del_list=( str(f) for f in files if os.path.getsize(f)//(2**20) > 500 )
        for file in del_list:
            output.write( "  %s  |  %s \n" %(str(direc),file))
    if __name__=="__main__" :
       do_stuff(str(sys.argv[1]))

When running it, the stack trace is:

       C:\Users\d\Desktop>python cleaner.py C:\
       Traceback (most recent call last):
       File "cleaner.py", line 35, in <module>
           do_stuff(str(sys.argv[1]))
       File "cleaner.py", line 32, in do_stuff
           for file in del_list:
       File "cleaner.py", line 31, in <genexpr>
           del_list=( str(f) for f in files if os.path.getsize(f)//(2**20) > 500 )
       File "C:\Python27\lib\genericpath.py", line 49, in getsize
           return os.stat(filename).st_size
       WindowsError: [Error 2] The system cannot find the file specified: '1Clickfolder
       test.txt'

What does the error mean ? Is there a simpler way of doing things ?

Upvotes: 0

Views: 111

Answers (1)

Messa
Messa

Reputation: 25181

The function walk_free(path) generates tuples of (path, filenames). The filename is just the filename, it does not include full path to that file.

Try to replace this

os.path.getsize(f)

with this:

os.path.getsize(os.path.join(direc, f))

Upvotes: 2

Related Questions