您的位置:首页 > 编程语言 > Python开发

可爱的python习题(四)

2012-07-06 22:09 330 查看
1,实现遍历所有指定目录文件,并找出找用空间最大的前3个文件

#!/usr/bin/python
#coding:utf-8
#filename:cdays-exercise.py
import os,sys
def get_top_three(path):
all_file={}#初始化一个字典数据结构
for root,dirs,files in os.walk(path):
for onefile in files:
fname=os.path.join(root,onefile)#字符串进行柔和
fsize=os.stat(fname).st_size
if all_file.has_key(fsize):#这里如果有相同大小的则合并起来
all_file[fsize].append(fname)
else:
all_file[fsize]=[fname]
fsize_key=all_file.keys()
fsize_key.sort()
#               print all_file  #测试用
result=[]#初始化一个列表
for i in [-1,-2,-3]:#排序算法
for j in all_file[fsize_key[i]]:
result.append((fsize_key[i],j))
return result

if __name__=="__main__":
if len(sys.argv)==1:
print "usage python cdays.py /test/python"
else:
abs_path=os.path.abspath(sys.argv[1])
if not os.path.isdir(abs_path):
print '%s is not exist' %abs_path
else:
top=get_top_three(abs_path)
for(s,f) in top:
print '%s---->%s\n' %(f,s)


测试结果:

root@zhou:/home/zhouqian/python# python cdays-exercise.py ./
/home/zhouqian/python/.cdays-exercise-2.py.swp---->12288

/home/zhouqian/python/www.baidu.com_utf-8---->8141

/home/zhouqian/python/cdays-exercise-2.py---->1334

遇到的问题:

首先是设计算法,知道自己要怎么做,1,遍历所有目录,2得出文件的大小3进行排序

遍历所有目录:os.walk(path)可以做到,然后迭代判断是否有子目录os.path.isdir(dir)

得出文件的大小:os.stat(dir).st_size

进行排序找出排前三的文件:这里需要自己想好数据结构来进行存储,先是使用字典,后排序的文件放在列表里

2,利用configparser,来格式化的存储

def iniTT(size_file):
cfg=RawConfigParser()
print size_file
index=1
for (s,f) in size_file:
cfg.add_section("%d" %index)
cfg.set("%d" %index,'Filename',f)
cfg.set("%d" %index,'Filesize',s)
index+=1
print index
cfg.write(open("cdays-exercise-2.result","w"))


然后使用form cdays-exercises.py import get_three_top使用它的方法

问题就是就是这个ConfigParser模块的使用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: