Python: Trying To Use 'count' To Limit The Amount Of Lines "print" Will Output
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:
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"