這篇將講述怎麼使用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:\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 123
parent is D:\temp, dirname is java
parent is D:\temp, filename is chydb_14.3_XiaZaiBa.zip
the 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 is Firefox39.7z
the full name of the file is D:\temp\Firefox39.7z
...省略
Python遍曆檔案夾和讀寫檔案的方法
1、讀取指定目錄下的所有檔案
2、讀取指定檔案,輸出檔案內容
3、建立一個檔案並儲存到指定目錄
Python寫代碼簡潔高效,實現以上功能僅用了40行左右的代碼~ 昨天用Java寫了一個寫入、建立、複製、重新命名檔案要將近60行代碼;
不過簡潔的代價是犧牲了一點點運行速度,但隨著硬體效能的提升,運行速度的差異會越來越小,直到人類無法察覺~
#-*- coding: UTF-8 -*-
'''
1、讀取指定目錄下的所有檔案
2、讀取指定檔案,輸出檔案內容
3、建立一個檔案並儲存到指定目錄
'''
import os
# 遍曆指定目錄,顯示目錄下的所有檔案名稱
def eachFile(filepath):
pathDir = os.listdir(filepath)
for allDir in pathDir:
child = os.path.join('%s%s' % (filepath, allDir))
print child.decode('gbk') # .decode('gbk')是解決中文顯示亂碼問題
# 讀取檔案內容並列印
def readFile(filename):
fopen = open(filename, 'r') # r 代表read
for eachLine in fopen:
print "讀取到得內容如下:",eachLine
fopen.close()
# 輸入多行文字,寫入指定檔案並儲存到指定檔案夾
def writeFile(filename):
fopen = open(filename, 'w')
print "\r請任意輸入多行文字"," ( 輸入 .號斷行符號儲存)"
while True:
aLine = raw_input()
if aLine != ".":
fopen.write('%s%s' % (aLine, os.linesep))
else:
print "檔案已儲存!"
break
fopen.close()
if __name__ == '__main__':
filePath = "D:\\FileDemo\\Java\\myJava.txt"
filePathI = "D:\\FileDemo\\Python\\pt.py"
filePathC = "C:\\"
eachFile(filePathC)
readFile(filePath)
writeFile(filePathI)