可爱的python习题(四)
2012-07-06 22:09
330 查看
1,实现遍历所有指定目录文件,并找出找用空间最大的前3个文件
测试结果:
遇到的问题:
首先是设计算法,知道自己要怎么做,1,遍历所有目录,2得出文件的大小3进行排序
遍历所有目录:os.walk(path)可以做到,然后迭代判断是否有子目录os.path.isdir(dir)
得出文件的大小:os.stat(dir).st_size
进行排序找出排前三的文件:这里需要自己想好数据结构来进行存储,先是使用字典,后排序的文件放在列表里
2,利用configparser,来格式化的存储
然后使用form cdays-exercises.py import get_three_top使用它的方法
问题就是就是这个ConfigParser模块的使用。
#!/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模块的使用。
相关文章推荐
- 笨方法学习Python-习题40: 字典, 可爱的字典
- 可爱的python课后习题(二)
- 可爱的python课后习题(三)
- 笨方法学Python 习题 39: 字典, 可爱的字典
- 可爱的python课后习题
- Python习题(二)
- 笨办法学Python笔记二——习题5,8
- 【廖雪峰python3.0】-课后习题:第2章:第一个python程序 and 第三章:python基础
- python-习题0~5
- 【廖雪峰python3.0】-课后习题:第5章:高级特性
- 笨方法学习Python-习题8:打印,打印
- python 笔记 函数和变量 《笨办法学Python》习题19 ——12.27
- 笨办法学python习题5更多的变量和打印
- 笨办法学python习题 6字符串和文本
- codewars习题(1),python3,playing with digits,6级,算法
- Python编程从入门到实践:习题4-13
- 【鱼C·零基础入门学习python】第16课到第22课习题答案
- 笨方法学python 习题39(列表)习题40(字典)
- python 手记9 〖笨方法学python习题30〗
- 可爱的 Python : Python中函数式编程,第一部分