這篇將講述怎么使用python來遍歷本地文件系統(tǒng),并把文件按文件大小從小到大排序的一個小例子
在這個例子中,主要會用到python內(nèi)置的和OS模塊的幾個函數(shù):
os.walk() : 該方法用來遍歷指定的文件目錄,返回一個三元tuple(dirpath, dirnames, filenames) ,其中dirpath為當(dāng)前目錄路徑,dirnames為當(dāng)前路徑下的文件夾,filenames為當(dāng)前路徑下的文件os.path.join() :可以用來連接目錄和文件名,這樣就可以得到某個文件的全路徑了os.path.getsize() :獲取制定文件的文件size ,配合os.path.join()使用, 如果傳入的為文件夾路徑,返回0Lsorted : 迭代一個items ,然后返回一個新的排序好的list,不會影響原對象
有了這幾個函數(shù)后,遍歷本地文件就非常簡單了,前三個函數(shù)不詳細(xì)說,
這邊主要講下第四個函數(shù)sorted 的用法:
講sorted前,先介紹一下iterable ,中文意思是迭代器
1. Python的幫助文檔中對iterable的解釋是:iteralbe指的是能夠一次返回它的一個成員的對象。
iteralbe主要包括3類:
2. python中對方法的講解:
其中 key, 和reverse為可選參數(shù)
key指定一個接收一個參數(shù)的比較函數(shù),用來從買個list元素中提取一個用于比較的關(guān)鍵字: 例如key=str.lower. 默認(rèn)值是None(直接比較元素)
reverse是一個布爾值。如果設(shè)置為True,列表元素將被倒序排列。
在原來的版本中還有個cmp參數(shù),現(xiàn)在已經(jīng)去掉了,兼容方案是 使用 functools.cmp_to_key() 把cmp函數(shù)轉(zhuǎn)換為key函數(shù)。
key 返回一個 lambda ,所謂 lambda就是一個匿名小函數(shù),lambda d: d[1] 對應(yīng)于代碼就是
def (d): return d[1]對應(yīng)到字典中,就是返回字典鍵值對中的 值,d[0]表示鍵,對字典使用sorted 會返回一個元祖 list
好了,基本的函數(shù)都講完了,下面附上例子的相應(yīng)代碼:
# -*-coding:utf-8-*-import osimport os.pathfilePath = 'D:/temp'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:/temp, dirname is 123parent is D:/temp, dirname is javaparent is D:/temp, filename is chydb_14.3_XiaZaiBa.zipthe full name of the file is D:/temp/chydb_14.3_XiaZaiBa.zipparent is D:/temp, filename is DriverGenius_green1.rarthe full name of the file is D:/temp/DriverGenius_green1.rarparent is D:/temp, filename is Firefox39.7zthe full name of the file is D:/temp/Firefox39.7z...省略
好了,大家如果有什么問題或者文件有什么錯誤的話,可以留言大家一起探討!
新聞熱點(diǎn)
疑難解答
圖片精選