python 小程序 查找最大的python文件
1. 扫描标准库目录
I 通过glob模块遍历一个目录下面的所有文件,glob接收shell中常用文件名模式语法:“?”代表任何单个字符,*代表任意字符
1 import glob 2 import os 3 import sys 4 5 dirname = '/usr/lib/python3.5' if len(sys.argv) == 1 else sys.argv[1] 6 allsize = [] 7 8 allpy = glob.glob(dirname + os.sep + '*.py') 9 for filename in allpy: 10 filesize = os.path.getsize(filename) 11 allsize.append((filesize, filename)) 12 13 allsize.sort() 14 print(allsize[-2:])
2. 扫描标准目录树
I 通过os.walk方法来循环遍目录树
1 import os 2 import pprint 3 4 dirname = '/usr/lib/python3.5' 5 6 allsize = [] 7 for (curDir, subDir, fileHere) in os.walk(dirname): 8 print(curDir) 9 for filename in fileHere: 10 if filename.endswith('.py'): 11 fullname = os.path.join(curDir,filename) 12 filesize = os.path.getsize(fullname) 13 allsize.append((filesize,fullname)) 14 15 allsize.sort(key= lambda x:x[0]) 16 pprint.pprint(allsize[-2:])
3. 扫描模块搜索路径
通过sys.path来查找,sys.path包含了所有导入的模块
1 import sys 2 import os 3 import pprint 4 5 allSize = [] 6 visited = {} 7 for srcDir in sys.path: 8 for(curDir, subDir, fileHere) in os.walk(srcDir): 9 curDir = os.path.normpath(curDir) 10 fixCase = os.path.normcase(curDir) 11 if fixCase in visited: 12 continue 13 else: 14 visited[fixCase] = True 15 for filename in fileHere: 16 if filename.endswith('.py'): 17 pypath = os.path.join(curDir, filename) 18 try: 19 pysize = os.path.getsize(pypath) 20 except os.error as e: 21 print(e) 22 else: 23 pylines = len(open(pypath, 'rb').readlines()) 24 allSize.append((pysize, pylines, pypath)) 25 26 allSize.sort(key=lambda x:x[0]) 27 pprint.pprint(allSize[-2:])