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

这篇将讲述怎么使用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 new sorted list 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-*-
import os
import os.path

filePath = 'D:	emp'

fileList = []
fileMap = {}
size = 0

# 遍历filePath下的文件、文件夹(包括子目录)
for parent, dirnames, filenames in os.walk(filePath):
    for dirname in dirnames:
        print('parent is %s, dirname is %s' % (parent, dirname))

    for filename in filenames:
        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=lambda d: d[1], reverse=False)
for filename, size in b:
    print("filename is %s , and size is %d" % (filename, size))

 大概输入如下:

parent is D:	emp, dirname is 123
parent is D:	emp, dirname is java
parent is D:	emp, filename is chydb_14.3_XiaZaiBa.zip
the full name of the file is D:	empchydb_14.3_XiaZaiBa.zip

parent is D:	emp, filename is DriverGenius_green1.rar
the full name of the file is D:	empDriverGenius_green1.rar

parent is D:	emp, filename is Firefox39.7z
the full name of the file is D:	empFirefox39.7z
...省略

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

原文地址:https://www.cnblogs.com/vhua/p/python_2.html