【程序员技术练级】学习一门脚本语言python(二)遍历本地文件系统

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

这篇将讲述怎么使用python来遍历本地文件系统,并把文件按文件大小从小到大排序的一个小例子

在这个例子中,主要会用到python内置的和OS模块的几个函数:

os.walk() :该方法用来遍历指定的文件目录,返回一个三元tuple(dirpath, dirnames, filenames) ,其中dirpath为当前目录路径,dirnames为当前路径下的文件夹,filenames为当前路径下的文件

os.path.join() :可以用来连接目录和文件名,这样就可以得到某个文件的全路径了

os.path.getsize() :获取制定文件的文件size ,配合os.path.join()使用, 如果传入的为文件夹路径,返回0L

sorted :迭代一个items,然后返回一个新的排序好的list,不会影响原对象

有了这几个函数后,遍历本地文件就非常简单了,前三个函数不详细说,

这边主要讲下第四个函数sorted的用法:

讲sorted前,先介绍一下iterable,中文意思是迭代器

1. Python的帮助文档中对iterable的解释是:iteralbe指的是能够一次返回它的一个成员的对象。

iteralbe主要包括3类:

第一类是所有的序列类型,比如list(列表)、str(字符串)、tuple(元组)。

第二类是一些非序列类型,比如dict(字典)、file(文件)。

第三类是你定义的任何包含__iter__()或__getitem__()方法的类的对象。

2. python中对sorted方法的讲解:

sorted(iterable[, key][, reverse])作用:Return a newsortedlist from the items in iterable.

其中 key, 和reverse为可选参数

key指定一个接收一个参数的比较函数,用来从买个list元素中提取一个用于比较的关键字: 例如key=str.lower. 默认值是None(直接比较元素)

reverse是一个布尔值。如果设置为True,列表元素将被倒序排列。

在原来的版本中还有个cmp参数,现在已经去掉了,兼容方案是使用functools.cmp_to_key()把cmp函数转换为key函数。

key 返回一个 lambda ,所谓 lambda就是一个匿名小函数,lambda d: d[1] 对应于代码就是

def (d):

return d[1]

对应到字典中,就是返回字典键值对中的 值,d[0]表示键,对字典使用sorted会返回一个元祖 list

好了,基本的函数都讲完了,下面附上例子的相应代码:

#-*-coding:utf-8-*-importosimportos.path

filePath='D:\temp'fileList=[]

fileMap={}

size=0#遍历filePath下的文件、文件夹(包括子目录)forparent, dirnames, filenamesinos.walk(filePath):fordirnameindirnames:PRint('parent is %s, dirname is %s'%(parent, dirname))forfilenameinfilenames:print('parent is %s, filename is %s'%(parent, filename))print('the full name of the file is %s'%os.path.join(parent, filename))

size=os.path.getsize(os.path.join(parent, filename))

fileMap.setdefault(os.path.join(parent, filename), size)print("all size is %d"%size)

b= sorted(fileMap.items(), key=lambdad: d[1], reverse=False)forfilename, sizeinb:print("filename is %s , and size is %d"% (filename, size))

大概输入如下:

parent is D:\temp, dirname is 123parent is D:\temp, dirname isjavaparent is D:\temp, filename is chydb_14.3_XiaZaiBa.zipthe full name of the file is D:\temp\chydb_14.3_XiaZaiBa.zip

parent is D:\temp, filename is DriverGenius_green1.rar

the full name of the file is D:\temp\DriverGenius_green1.rar

parent is D:\temp, filename isFirefox39.7z

the full name of the file is D:\temp\Firefox39.7z

...省略

好了,大家如果有什么问题或者文件有什么错误的话,可以留言大家一起探讨!

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