Python之练习Demo

遍历本地文件系统 (sys, os, path),例如写一个程序统计一个目录下所有文件大小并按各种条件排序并保存结果,代码如下:

#coding:GBK
import os;

def SortList(item):
    return item[1];

def ReadSize(fileName):
    return float(os.path.getsize(fileName));

def WriteAll(path):
    l = []
    loger = open("test.log","w");
    writer = open("path.txt","w");
    reader = open("path.txt","r");
    size = 0;
    for root,dirs,files in os.walk(path):
        for filesPath in files:
            try:
                fllePath = os.path.join(root,filesPath);
                fileSize = float(ReadSize(fllePath)/1024);
                size += fileSize;
                x = (fllePath,int(fileSize));
                l.append(x);
            except:
                loger.write("读取:"+os.path.join(root,filesPath)+"文件大小失败!\n");
                continue;
    l = sorted(l,key=SortList,reverse=True);
    for item in l:
        strTmp = "";
        if float(item[1]/1024) > 1024:
            strTmp = item[0]+" "+str(int(float(item[1]/1024/1024)))+"GB\n";
        elif item[1] > 1024:
            strTmp = item[0]+" "+str(int(float(item[1]/1024)))+"MB\n";                           
        else:
            strTmp = item[0]+" "+str(item[1])+"KB\n";
                                     
        writer.write(strTmp);
    writer.write("共使用磁盘空间:"+str(float(size/1024))+"MB");
    loger.close();
    writer.close();
    print(reader.read());
    reader.close();

fileName = os.getcwd();
WriteAll(fileName);
raw_input("END...");

 

转载于:https://www.cnblogs.com/ysjshrine/p/4299268.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值