目錄周遊
包:
os os.path
函數:
os.listdir(dirname):列出dirname下的目錄和檔案
os.getcwd():獲得目前工作目錄
os.curdir:傳回目前目錄('.')
os.chdir(dirname):改變工作目錄到dirname
os.path.isdir(name):判斷name是不是一個目錄,name不是目錄就傳回false
os.path.isfile(name):判斷name是不是一個檔案,不存在name也傳回false
os.path.exists(name):判斷是否存在檔案或目錄name
os.path.getsize(name):獲得檔案大小,如果name是目錄傳回0
os.path.abspath(name):獲得絕對路徑
os.path.normpath(path):規範path字元串形式
os.path.split(name):分割檔案名與目錄(事實上,如果你完全使用目錄,它也會将最後一個目錄作為檔案名而分離,同時它不會判斷檔案或目錄是否存在)
os.path.splitext():分離檔案名與擴充名
os.path.join(path,name):連接配接目錄與檔案名或目錄
os.path.basename(path):傳回檔案名
os.path.dirname(path):傳回檔案路徑
遞歸法
#coding:utf8
import os
def dirList(path,allfile):
filelist=os.listdir(path)
for filename in filelist:
filepath=os.path.join(path,filename)
if os.path.isdir(filepath):
dirList(filepath,allfile)
allfile.append(filepath)
allfile=[]
dirList('D:\\pythonPro\\test',allfile)
print allfile
os.walk()法
os.walk(path)傳回一個生成器,可以用next()方法,或者for循環通路該生成器的每一個元素。 他的每個部分都是一個三元組,('目錄x',[目錄x下的目錄list],[目錄x下面的檔案list])
path='D:\\pythonPro\\test'
allfile1=[]
g=os.walk(path)
for root,dirs,files in os.walk(path):
for filename in files:
allfile1.append(os.path.join(root,filename))
for dirname in dirs:
allfile1.append(os.path.join(root,dirname))
print allfile1
os.walk()方法操作更加友善,實用。