Skip to content Skip to sidebar Skip to footer

Python: Trying To Use 'count' To Limit The Amount Of Lines "print" Will Output

I have a script that will walk a system directory, and get the files sizes in that directory. it then sorts by the file size(descending), takes two arguments. The first arg is the

Solution 1:

FWIW, the repr module has tools to display a list while limiting the number of lines of output.

Solution 2:

If mycnt is a string, not an integer (which it is when read directly from sys.argv), your loop will never end.

Solution 3:

You should have an if instead of while.

You want to exit the program ifcount <= mycnt.

Solution 4:

You added the else clause to the while loop. It will execute only if the while loop never executes.

Your while loop terminates as count increases past mycnt, and anoter iteration of for loop is executed. Mabe you just don't notice it ­— your for loop may take long.

Solution 5:

Larry Lustig has already hit the nail on the head regarding mycnt, but your check to see if you've hit the limit is also wrong (as Hamish points out).

Rather than if (count <= mycnt):, you could use a slice like [:maximum], removing the need for the count variable. Speaking of variables, I suggest that you would benefit from some better-named variables. Viz:

#!/usr/bin/env python

import sys
import os

rootdir = sys.argv[1]
maximum = int(sys.argv[2])

print'Printing the biggest ', maximum, 'files in', rootdir, '...'

filedict = {}
for root, _, files inos.walk(rootdir):
    for filename in files:
        filepath = os.path.join(root, filename)
        filesize = os.path.getsize(filepath)
        filedict[filepath] = filesize

sorted_by_size = sorted(filedict.iteritems(), key=lambda(path, size): (size, path), reverse=True)
forpath, size in sorted_by_size[:maximum]:
     print"(%8s)      (%-8s)" % (size, path)

Post a Comment for "Python: Trying To Use 'count' To Limit The Amount Of Lines "print" Will Output"