Python:尝试使用'count'来限制“print”输出的行数

时间:2011-11-12 02:50:43

标签: python count while-loop

我有一个脚本,它将遍历系统目录,并获取该目录中的文件大小。然后按文件大小排序(降序),接受两个参数。第一个arg是系统路径,第二个arg是一个整数,用于将输出限制为整数计数。

我正在使用while循环来限制打印输出,但它会陷入无限循环......很明显,有些东西是错的,但是我无法看到它。

#!/usr/bin/python

import sys
import os

#Grab arguments 
mydir = sys.argv[1]
mycnt = sys.argv[2]

print mydir 
print mycnt
#set base dir
root_path = mydir


fileSize = 0
rootdir = mydir
filedict = dict()
count = 0

for root, dirs, files in os.walk(rootdir):
    for file in files:
        filepath = os.path.join(root,file)
        filesize = fileSize + os.path.getsize(filepath)
        filedict[filepath] = filesize


for key, value in sorted(filedict.iteritems(), key=lambda (key,val): (val,key), reverse=True):
    while (count <= mycnt):
        print "(%8s)" "     (%-8s)" % (value, key)
        count += 1
    else:
        sys.exit()

5 个答案:

答案 0 :(得分:4)

FWIW, repr 模块具有显示列表的工具,同时限制输出行数。

答案 1 :(得分:3)

如果mycnt是一个字符串,而不是整数(直接从sys.argv读取时),那么你的循环永远不会结束。

答案 2 :(得分:2)

您应该有一个if而不是while

如果 count <= mycnt,您想要退出程序

答案 3 :(得分:1)

您将else子句添加到while循环中。它仅在while循环从不执行时执行。

while循环终止,count增加超过mycnt,并执行for循环的另一次迭代。 Mabe你只是没注意到它 - 你的for循环可能需要很长时间。

答案 4 :(得分:1)

关于mycnt

Larry Lustig has already hit the nail on the head,但检查您是否达到了限制也是错误的(Hamish points out)。

而不是if (count <= mycnt):,您可以使用[:maximum] count,而不需要#!/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 in os.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) for path, size in sorted_by_size[:maximum]: print "(%8s) (%-8s)" % (size, path) 变量。说到变量,我建议您从一些更好命名的变量中受益。 维兹

{{1}}