码迷,mamicode.com
首页 > 编程语言 > 详细

Python之练习Demo

时间:2015-03-11 12:13:08      阅读:222      评论:0      收藏:0      [点我收藏+]

标签:

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

 1 #coding:GBK
 2 import os;
 3 
 4 def SortList(item):
 5     return item[1];
 6 
 7 def ReadSize(fileName):
 8     return float(os.path.getsize(fileName));
 9 
10 def WriteAll(path):
11     l = []
12     loger = open("test.log","w");
13     writer = open("path.txt","w");
14     reader = open("path.txt","r");
15     size = 0;
16     for root,dirs,files in os.walk(path):
17         for filesPath in files:
18             try:
19                 fllePath = os.path.join(root,filesPath);
20                 fileSize = float(ReadSize(fllePath)/1024);
21                 size += fileSize;
22                 x = (fllePath,int(fileSize));
23                 l.append(x);
24             except:
25                 loger.write("读取:"+os.path.join(root,filesPath)+"文件大小失败!");
26                 continue;
27     l = sorted(l,key=SortList,reverse=True);
28     for item in l:
29         strTmp = "";
30         if float(item[1]/1024) > 1024:
31             strTmp = item[0]+" "+str(int(float(item[1]/1024/1024)))+"GB\n";
32         elif item[1] > 1024:
33             strTmp = item[0]+" "+str(int(float(item[1]/1024)))+"MB\n";                           
34         else:
35             strTmp = item[0]+" "+str(item[1])+"KB\n";
36                                      
37         writer.write(strTmp);
38     writer.write("共使用磁盘空间:"+str(float(size/1024))+"MB");
39     loger.close();
40     writer.close();
41     print(reader.read());
42     reader.close();
43 
44 fileName = os.getcwd();
45 WriteAll(fileName);
46 raw_input("END...");

 

Python之练习Demo

标签:

原文地址:http://www.cnblogs.com/ysjshrine/p/4299268.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!