zoukankan      html  css  js  c++  java
  • 【python学习】遍历目录及写配置文件

    一、题目

    编程实现以下功能并进行最大化的优化:遍历指定目录下的所有文件,找出其中占用空间最大的前3个文件。 利用ConfigParser,将上述题目中产生的结果按照cdays+1-my.ini格式存储到文件cdays+1-result.txt中。

    二、难点

    1.os.stat获取大小相关信息

    2.os.walk遍历文件

    3.configparser使用

    三、实现

    #-*- coding:utf-8 -*-
    #FileName:top3.py
    #Author:Xue Weiwei@USTC
    #Last-Modify:2012-5-16
    '''获取指定目录下占用空间最大的top3文件,并写入到配置文件
    @note:os.stat获取相关信息,os.walk遍历,ConfigPraser的使用'''
    import os
    import sys
    from ConfigParser import RawConfigParser as rcp
    def gettop3(path):
    '''
    给定目录下的前三个大小的文件
    @param path: 给定路径
    '''
    sizeinfo={}
    for root,dirs,files in os.walk(path):
    for onefile in files:
    fname=os.path.join(root,onefile)
    fsize=os.stat(fname).st_size
    sizeinfo[fname]=fsize
    # print sorted(sizeinfo.values())
    #用sorted函数进行排序,使用lambda表达式
    result = sorted(sizeinfo.items(),key=lambda sizeinfo:sizeinfo[1])
    #print result
    print "%s\t-->\t%s"%(result[0][0],result[0][1])
    print "%s\t-->\t%s"%(result[1][0],result[1][1])
    print "%s\t-->\t%s"%(result[2][0],result[2][1])
    return result[:3]
    #print top3
    def toini(list):
    '''
    将结果写入ini文件,使用ConfigParser
    @param list: 输入前三个文件的列表
    '''
    cfg=rcp()
    index=1
    for (f,s) in list:
    cfg.add_section("第%d个" % index)
    cfg.set("第%d个" % index,"FileName",f)
    cfg.set("第%d个" % index,"Size",s)
    index+=1
    cfg.write(open("top3-result.ini","w"))
    if __name__=='__main__':
    if len(sys.argv)!=2:
    print "Usage: python top3.py yourpath"
    else:
    toini(gettop3(sys.argv[1]))

    四、参考

    1.http://woodpecker.org.cn/diveintopython/power_of_introspection/lambda_functions.html

    2.http://www.cnblogs.com/vivilisa/archive/2009/03/01/1400972.html

  • 相关阅读:
    钉钉outgoing机器人小项目开发
    js根据cookie判断,一天之内只弹出一次弹窗
    js倒计时功能
    jquery的$().each,$.each的区别
    VS代码提示自动高亮
    winform当前屏幕大小
    动态增删改控件
    datagridveiw样式
    sql 语句 提取中文的首字母
    按键监听及重写
  • 原文地址:https://www.cnblogs.com/xweiwei/p/2732532.html
Copyright © 2011-2022 走看看