列出特定文件夹下面小于特定大小的文件
#!/usr/bin/env python
"""
FindSmallFile.py
SYNOPSIS
Print the file name which size is small
than the cutoff value in the given path.
DESCRIPTION
python FindSmallFile.py -d path_to_file -e cutoff_value
OPTIONS
-e : the cutoff value (eg. 1K, 2.5K, 1M, 2,G ...)
-d : the path of the file in (eg. /home/quwb/)
-? : display help (--? and --help do the same thing).
-v : verbose output
EXAMPLES
python FindSmallFile.py -d ./ -e 1.2k
AUTHOR
Wubin Qu
LICENSE
This script is under the GPL licenses.
"""
import sys, os, getopt, traceback
import time
import re
import string
VERBOSE = False
def exit_with_usage ():
print globals()['__doc__']
os._exit(1)
def parse_args (options='', long_options=[]):
try:
optlist, args = getopt.getopt(sys.argv[1:], options+'?', long_options+['help','?'])
except Exception, e:
print str(e)
exit_with_usage()
options = dict(optlist)
if [elem for elem in options if elem in ['-?','--?','--help']]:
exit_with_usage()
return (options, args)
def main ():
global VERBOSE
(options, args) = parse_args('vd:e:')
if '-v' in options:
VERBOSE = True
else:
VERBOSE = False
if options.has_key('-d') and options['-d'] != '':
path = options['-d']
else:
print 'option "-d" is needed'
exit_with_usage()
if options.has_key('-e') and options['-e'] != '':
cutoff = options['-e']
else:
print 'option "-e" is needed'
exit_with_usage()
cutoff = str(cutoff)
if cutoff.find('K') >= 0:
cutoff = re.sub('K', '', cutoff)
cutoff = string.atoi(cutoff) * 1024
elif cutoff.find('M') >= 0:
cutoff = re.sub('M', '', cutoff)
cutoff = string.atoi(cutoff) * 1024**2
elif cutoff.find('G') >= 0:
cutoff = re.sub('G', '', cutoff)
cutoff = string.atoi(cutoff) * 1024**3
elif re.search('\D', cutoff):
print 'cutoff arguments contains some odd characters'
exit_with_usage()
else:
cutoff = string.atoi(cutoff)
for root, dirs, files in os.walk(path):
for file in files:
size = os.path.getsize(file)
if not size:
print '%s size: 0.' % file
else:
if size <= cutoff:
print '%s size: %d' % (file, size)
if __name__ == '__main__':
try:
start_time = time.time()
if VERBOSE: print time.asctime()
main()
if VERBOSE: print time.asctime()
if VERBOSE: print 'TOTAL TIME IN MINUTES:',
if VERBOSE: print (time.time() - start_time) / 60.0
sys.exit(0)
except SystemExit, e:
raise e
except Exception, e:
print 'ERROR, UNEXPECTED EXCEPTION'
print str(e)
traceback.print_exc()
os._exit(1)