Python之练习Demo

王朝学院·作者佚名  2016-08-27
窄屏简体版  字體: 小  |  中  |  大  |  超大  

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

#coding:GBKimportos;defSortList(item):returnitem[1];defReadSize(fileName):returnfloat(os.path.getsize(fileName));defWriteAll(path):

l=[]

loger= open("test.log","w");

writer= open("path.txt","w");

reader= open("path.txt","r");

size=0;forroot,dirs,filesinos.walk(path):forfilesPathinfiles: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);foriteminl:

strTmp="";iffloat(item[1]/1024) > 1024:

strTmp= item[0]+""+str(int(float(item[1]/1024/1024)))+"GB\n";elifitem[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...");

 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
 
© 2005- 王朝網路 版權所有 導航